一、

消息的广播需要exchange:exchange是一个转发器,其实把消息发给RabbitMQ里的exchange

fanout: 所有bind到此exchange的queue都可以接收消息,广播

direct: 通过routingKey和exchange决定的那个唯一的queue可以接收消息

topic:所有符合routingKey(此时可以是一个表达式)的routingKey所bind的queue可以接收消息

headers:通过headers来决定把消息发给哪些queue,用的比较少

原理图:

发布者端:

'''
发布者publisher
'''
import pika
import sys connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs', # exchange名字为logs
type='fanout')
# 通过命令行自己输入消息,没输入就是hello world
message = ' '.join(sys.argv[1:]) or "info: Hello World!"
# 广播不需要写queue,routing_key为空
channel.basic_publish(exchange='logs',
routing_key='',
body=message)
print("send :", message)
connection.close()

订阅者端:

'''
订阅者subscriber
'''
import pika connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs',
type='fanout')
# 不指定queue名字,rabbit会随机分配一个唯一的queue,
# exclusive=True会在使用此queue的消费者断开后,自动将queue删除
# 发送端没有声明queue,为什么接收端需要queue?看上面原理图就明白
result = channel.queue_declare(exclusive=True)
# 拿到的随机的queue名字
queue_name = result.method.queue
# 需要知道从哪个转发器上去收所以需要绑定
channel.queue_bind(exchange='logs',
queue=queue_name)
print("Wait for logs...")
def callback(ch, method, properties, body):
print("received:", body)
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming()

运行结果:

'''
先启动发布者,再启动订阅者,为什么订阅者收不到信息?
原理类似于收音机收听广播:
订阅者相当于收音机,发布者相当于广播信号
所以这个接收是实时的,订阅者启动之后,才能收到发布者发出的广播
'''

最新文章

  1. Linux(CentOs6.4)安装Git
  2. Apache配置日志功能
  3. Mysql分区技术
  4. 使用Rxjava缓存请求
  5. sql server 中将由逗号“,”分割的一个字符串,转换为一个表,并应用与 in 条件
  6. 转载:Unobtrusive JavaScript in ASP.NET MVC 3 隐式的脚本在MVC3
  7. 按钮点击WIN8 磁贴效果
  8. Binary search for the first element greater than target
  9. JVM原理
  10. java复习-多线程
  11. JSP基本语法--实例演练
  12. 关于svg
  13. our happy ending(状压dp)
  14. volatile的使用场景
  15. falsk_蓝图(blueprint)
  16. LaTeX技巧10:LaTeX数学公式输入初级入门
  17. boost asio 一个聊天的基本框架
  18. php输出日志
  19. django学习笔记(1)
  20. localStorage注册页面A注册数据在本地储存并在B页面打开

热门文章

  1. Redis学习——数据结构介绍(四)
  2. Android--从系统Camera和Gallery获取图片优化
  3. 带着新人学springboot的应用04(springboot+mybatis+redis 完)
  4. 如何零基础开始自学Python编程
  5. 使用mpvue开发小程序教程(四)
  6. C#2.0 委托
  7. 深入浅出ASP.NET Core系列(入门篇)
  8. Docker系列01—容器的发展历程---Docker的生态圈
  9. shell编程练习(四): 笔试31-68
  10. python3.6 pip 出现locations that require TLS/SSL异常解决方案