rabbitMQ direct实现广播
原理图:
消息广播者:
''' exchange 类型: fanout:所有bind到此exchange 的queue 都可以接收到消息 direct: 通过routingkey和exchange 决定的那个唯一的queue 可以接收到消息 接收端可以接收指定级别的消息:info , warning , error topic: 所有符合routingkey的routingkey所bind的queue 可以接收消息 表达式符合说明: #代表一个或多个字符 *代表任何字符 header:通过headers来决定把消息发给哪些queue ''' import pika connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.exchange_declare(exchange='direct_logs',exchange_type='direct') msg = "using direct .." #消息级别 severity = 'info' channel.basic_publish(exchange='direct_logs',routing_key=severity,body=msg) print('send %s:%s'%(severity,msg)) channel.close()
消息接收者:
import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.exchange_declare(exchange='direct_logs',exchange_type='direct') result = channel.queue_declare(exclusive=True) queueName = result.method.queue severities = 'info' channel.queue_bind(exchange='direct_logs',queue=queueName,routing_key=severities) def callback(ch , method ,properties, body): print("接收:",body) print("routingKey:", method.routing_key) channel.basic_consume(callback,queue=queueName,no_ack=True) channel.start_consuming() channel.close()
posted on 2017-12-22 17:28 gaizhongfeng 阅读(534) 评论(0) 编辑 收藏 举报