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