rmq.py 6.03 KB
Newer Older
1 2 3 4
import json

import pika

5
host='localhost' # TODO Handle host being passed in
6 7 8 9 10 11 12 13 14

# -------------------------------------------------------------------------------------------------------------------------------------------------------------

def pika_connect(host):
    connection = pika.BlockingConnection(pika.ConnectionParameters(host))
    channel = connection.channel()
    return connection, channel


15
def setup_queue(channel, queue_name=''):
16 17 18
    channel.queue_declare(queue=queue_name, exclusive=False, durable=True) # exclusive means the queue can only be used by the connection that created it


James Kirk's avatar
James Kirk committed
19
def fanout_exchange(channel, exchange_name):
20
    channel.exchange_declare(exchange=exchange_name, exchange_type='fanout', durable=True)
21 22


James Kirk's avatar
James Kirk committed
23
def topic_exchange(channel, exchange_name):
24
    channel.exchange_declare(exchange=exchange_name, exchange_type='topic', durable=True)
25 26


27
def deliver_to_exchange(channel, body, exchange_name, topic=None):
28 29
    if topic is None:
        fanout_exchange(channel=channel, exchange_name=exchange_name)
30 31 32 33 34 35 36 37
        channel.basic_publish(
            exchange=exchange_name,
            routing_key='', 
            body=body, 
            properties=pika.BasicProperties(
                delivery_mode=pika.spec.PERSISTENT_DELIVERY_MODE
            )
        )
38 39
    else:
        topic_exchange(channel=channel, exchange_name=exchange_name, topic=topic)
40 41 42 43 44 45 46 47
        channel.basic_publish(
            exchange=exchange_name,
            routing_key=topic, 
            body=body, 
            properties=pika.BasicProperties(
                delivery_mode=pika.spec.PERSISTENT_DELIVERY_MODE
            )
        )
48 49 50 51 52 53 54 55

# -------------------------------------------------------------------------------------------------------------------------------------------------------------

def write_to_queue(queue_name, msg):
    # write a single message to a queue
    connection, channel = pika_connect(host=host)
    setup_queue(channel=channel, queue_name=queue_name)

56 57 58 59 60 61 62 63 64
    channel.basic_publish(
        exchange='', 
        routing_key=queue_name, 
        body=msg,
        properties=pika.BasicProperties(
            delivery_mode=pika.spec.PERSISTENT_DELIVERY_MODE
        )
    )

65 66 67 68
    connection.close()


def read_from_queue(queue_name, max_msgs):
69
    # get messages off of a queue until the queue is empty or max_msgs is hit
70 71 72 73 74 75 76 77 78 79
    connection, channel = pika_connect(host=host)

    setup_queue(channel=channel, queue_name=queue_name)

    messages = []
    while len(messages) < max_msgs:
        method_frame, header_frame, body = channel.basic_get(queue_name)
        if method_frame:
            print(method_frame, header_frame, body)
            channel.basic_ack(method_frame.delivery_tag)
James Kirk's avatar
James Kirk committed
80 81 82 83
            try:
                messages.append(json.loads(body.decode()))
            except:
                messages.append(body.decode())
84 85 86 87 88 89 90 91 92 93 94 95
        else:
            print("No message returned")
            break

    connection.close()
    return messages


def broadcast(queue_name, exchange_name):
    # read from a queue, forward onto a 'fanout' exchange
    _, channel = pika_connect(host=host)

96
    setup_queue(channel=channel, queue_name=queue_name)
97 98 99 100 101

    def broadcast_callback(ch, method, properties, body):
        deliver_to_exchange(channel=ch, body=body, exchange_name=exchange_name)
        ch.basic_ack(delivery_tag=method.delivery_tag)

102 103 104 105 106
    try:
        channel.basic_consume(queue=queue_name, on_message_callback=broadcast_callback)
        channel.start_consuming()
    except pika.exceptions.AMQPChannelError as err:
        print("Caught a channel error: {}, stopping...".format(err))
107 108


James Kirk's avatar
James Kirk committed
109
def forward(from_queue, to_queue):
110 111 112
    # read from a queue, forward onto a different queue
    _, channel = pika_connect(host=host)

James Kirk's avatar
James Kirk committed
113 114
    setup_queue(channel=channel, queue_name=from_queue)
    setup_queue(channel=channel, queue_name=to_queue)
115 116

    def forward_callback(ch, method, properties, body):
117 118
        channel.basic_publish(
            exchange='',
James Kirk's avatar
James Kirk committed
119
            routing_key=to_queue, 
120 121 122 123 124
            body=body,
            properties=pika.BasicProperties(
                delivery_mode=pika.spec.PERSISTENT_DELIVERY_MODE
            )
        )
125 126
        ch.basic_ack(delivery_tag=method.delivery_tag)

127
    try:
James Kirk's avatar
James Kirk committed
128
        channel.basic_consume(queue=from_queue, on_message_callback=forward_callback)
129 130 131
        channel.start_consuming()
    except pika.exceptions.AMQPChannelError as err:
        print("Caught a channel error: {}, stopping...".format(err))
132 133 134 135 136 137 138 139 140 141 142 143 144 145


def publish(queue_name, exchange_name):
    # read from a queue, forward onto a 'topic' exchange
    _, channel = pika_connect(host=host)

    setup_queue(channel=channel, queue_name=queue_name)

    def publish_callback(ch, method, properties, body):
        message = json.loads(body.decode())
        topic = message["topic"]
        deliver_to_exchange(channel=ch, body=body, exchange_name=exchange_name, topic=topic)
        ch.basic_ack(delivery_tag=method.delivery_tag)

146 147 148 149 150
    try:
        channel.basic_consume(queue=queue_name, on_message_callback=publish_callback)
        channel.start_consuming()
    except pika.exceptions.AMQPChannelError as err:
        print("Caught a channel error: {}, stopping...".format(err))
151 152 153 154 155


def subscribe(queue_name, exchange_name, topic=None):
    # setup bindings between queue and exchange, 
    # exchange_type is either 'fanout' or 'topic' based on if the topic arg is passed
156
    connection, channel = pika_connect(host=host)
157

James Kirk's avatar
James Kirk committed
158 159
    setup_queue(channel=channel, queue_name=queue_name)

160
    if topic is None:
James Kirk's avatar
James Kirk committed
161 162
        fanout_exchange(channel=channel, exchange_name=exchange_name)
        channel.queue_bind(exchange=exchange_name, queue=queue_name)
163
    else:
James Kirk's avatar
James Kirk committed
164 165
        topic_exchange(channel=channel, exchange_name=exchange_name, topic=topic)
        channel.queue_bind(exchange=exchange_name, queue=queue_name, routing_key=topic)
166

167 168
    connection.close()

169 170 171 172 173 174 175 176 177

def listen(queue_name, callback):
    # subscribe client to a queue, using the callback arg
    _, channel = pika_connect(host=host)

    setup_queue(channel=channel, queue_name=queue_name)

    channel.basic_consume(queue=queue_name, on_message_callback=callback)
    channel.start_consuming()