python中RabbitMQ的使用(交换机,广播形式)

简介

如果要让每个接收端都能收到消息,此时需要将消息广播出去,需要使用交换机。

工作原理

消息发送端先将消息发送给交换机,交换机再将消息发送到绑定的消息队列,而后每个接收端都能从各自的消息队列里接收到信息。

示例代码

send2.py:

 1 #!/usr/bin/env python
 2 # coding=utf8
 3 # 每次消息都只会发送给其中一个接收端,如果需要将消息广播出去,让每个接收端都能收到,那么就要使用交换机
 4 # 定义交换机
 5 # 不是将消息发送到hello队列,而是发送到交换机
 6 
 7 import pika
 8 
 9 hostname = '192.168.1.133'
10 parameters = pika.ConnectionParameters(hostname)
11 connection = pika.BlockingConnection(parameters)
12 
13 channel = connection.channel()
14 # 定义交换机,设置类型为fanout
15 channel.exchange_declare(exchange='change_fan', type='fanout')
16 
17 # 将消息发送到交换机
18 # basic_publish方法的参数exchange被设定为相应交换机
19 # 因为是要广播出去,发送到所有队列,所以routing_key就不需要设定
20 channel.basic_publish(exchange='change_fan', routing_key='', body='Hello World!')
21 print " [x] Sent 'Hello World!'"
22 connection.close()

receive2.py:

 1 #!/usr/bin/env python
 2 # coding=utf8
 3 # 定义交换机
 4 # 随机生成一个临时队列,并绑定到交换机上,从而接收端从临时队列获取消息
 5 import pika
 6 
 7 hostname = '192.168.1.133'
 8 parameters = pika.ConnectionParameters(hostname)
 9 connection = pika.BlockingConnection(parameters)
10 
11 channel = connection.channel()
12 # 定义交换机,设置类型为fanout
13 channel.exchange_declare(exchange='change_fan', type='fanout')
14 
15 # queue_declare的参数exclusive=True表示当接收端退出时,销毁临时产生的队列,这样就不会占用资源。
16 result = channel.queue_declare(exclusive=True)
17 # 随机生成队列,并绑定到交换机上
18 queue_name = result.method.queue
19 channel.queue_bind(exchange='change_fan', queue=queue_name)
20 
21 
22 def callback(ch, method, properties, body):
23     print " [x] Received %r" % (body,)
24 
25 channel.basic_consume(callback, queue=queue_name, no_ack=True)
26 
27 print ' [*] Waiting for messages. To exit press CTRL+C'
28 channel.start_consuming()
原文地址:https://www.cnblogs.com/jfl-xx/p/7345975.html