• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
火磷
Memory will fade,but not notes.
博客园    首页    新随笔    联系   管理    订阅  订阅
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()

 

posted on 2017-08-11 14:57  火磷  阅读(1318)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3