mq 的direct 模式,在生产者中,绑定队列和路由key 和 发布的路由key 一定要一致。消费者和生产者的路由key 一致,当然一个队列也可以绑定多个key.
生产者
python 代码
import pika from pika.exchange_type import ExchangeType con = pika.BlockingConnection( pika.ConnectionParameters(host="localhost") ) # 创建通道 channel = con.channel() # 声明队列 result = channel.queue_declare(queue='sss') queue_name = result.method.queue # 声明交换机和交换机类型 channel.exchange_declare(exchange="direct_logs",exchange_type=ExchangeType.direct) # 绑定交换机和队列 routing_key = "info" channel.queue_bind(queue_name,"direct_logs",routing_key=routing_key) message = "oh my gold !" channel.basic_publish(exchange="direct_logs",routing_key=routing_key,body=message) con.close()
消费者
import pika con = pika.BlockingConnection( pika.ConnectionParameters(host="localhost") # 连接参数处,可以什么都不传,因为默认的值,默认的端口5672,默认的交换机,默认的虚拟机/,默认的用户名和默认的密码 ) channel = con.channel() channel.exchange_declare(exchange="direct_logs", exchange_type="direct") result = channel.queue_declare(queue="sss") queue_name = result.method.queue # 绑定交换机和路由 channel.queue_bind(exchange="direct_logs", queue=queue_name, routing_key="info") def callback(ch, method, properties, body): print("[x] %r:%r file_name = %s" % (method.routing_key, body,"----consumer_01")) channel.basic_consume(queue=queue_name,on_message_callback=callback,auto_ack=True) channel.start_consuming()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)