-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathamqp_example.py
63 lines (44 loc) · 1.37 KB
/
amqp_example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import pika
EXCHANGE_NAME = "my-exchange"
QUEUE_NAME = "my-queue"
def init_rabbitmq():
"""
Initializes the RabbitMQ environment used for this example
"""
conn = pika.BlockingConnection()
chan = conn.channel()
chan.exchange_declare(EXCHANGE_NAME, "direct")
chan.queue_declare(QUEUE_NAME, durable=True)
chan.queue_bind(QUEUE_NAME, EXCHANGE_NAME, "routing.key")
conn.close()
class Producer(object):
"""
An object that sends messages to a RabbitMQ broker
"""
def __init__(self, conn):
self.connection = conn
def send_message(self, msg, exch, routing_key):
chan = self.connection.channel()
chan.basic_publish(exch, routing_key, msg)
chan.close()
class Consumer(object):
"""
An object that reads messages from a RabbitMQ broker
"""
def __init__(self, conn):
self.connection = conn
def get_message(self, queue):
chan = self.connection.channel()
method_frame, _, body = chan.basic_get(queue)
if method_frame:
chan.basic_ack(method_frame.delivery_tag)
return body
def hello_world():
init_rabbitmq()
conn = pika.BlockingConnection()
p = Producer(conn)
p.send_message("Hello World!", EXCHANGE_NAME, "routing.key")
c = Consumer(conn)
print(c.get_message(QUEUE_NAME))
if __name__ == "__main__":
hello_world()