Hello world

参考官方代码示例

Producer示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import pika
import json

username = 'glance-rabbitmq-user'
password = 'glancepFAlXGtyZc7lTi0*'
host = 'osh-openstack-rabbitmq-rabbitmq-0.rabbitmq.openstack.svc.cluster.local'
port = 5672
vhost = 'glance'
exchange = 'demo'

credentials = pika.PlainCredentials(username, password)
connection = pika.BlockingConnection(
pika.ConnectionParameters(
host=host, port=port, virtual_host=vhost, credentials=credentials))
channel = connection.channel()
channel.exchange_declare(exchange=exchange, durable=True, exchange_type='fanout')

for i in range(10):
msg=json.dumps({'OrderId':"1000%s"%i})
channel.basic_publish(exchange=exchange, routing_key='', body=msg,
properties=pika.BasicProperties(delivery_mode=2))
print(msg)

connection.close()

Consumer示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import pika

username = 'glance-rabbitmq-user'
password = 'glancepFAlXGtyZc7lTi0*'
host = 'osh-openstack-rabbitmq-rabbitmq-0.rabbitmq.openstack.svc.cluster.local'
port = 5672
vhost = 'glance'
exchange = 'demo'

credentials = pika.PlainCredentials(username, password)
connection = pika.BlockingConnection(
pika.ConnectionParameters(
host=host, port=port, virtual_host=vhost, credentials=credentials))
channel = connection.channel()
result = channel.queue_declare('', exclusive=True)
channel.exchange_declare(exchange=exchange, durable=True, exchange_type='fanout')
channel.queue_bind(exchange=exchange, queue=result.method.queue)

def callback(ch, method, properties, body):
ch.basic_ack(delivery_tag=method.delivery_tag)
print(body.decode())

channel.basic_consume(result.method.queue, callback, auto_ack=False)
channel.start_consuming()

参考文档