美文网首页
路由模式direct

路由模式direct

作者: forjie | 来源:发表于2019-06-12 18:02 被阅读0次

与发布-订阅模式一样,消息发送到exchange中,消费者把队列绑定到exchange上

这种模式在exchange上添加添加了一个路由键(routing-key),生产者发布消息的时候添加路由键(routing-key),消费者绑定队列到交换机时添加键值(routing-key),这样就可以接收到对应的消息

总结: 通过不同的routing_key发布不同的数据

-生产者 send.py

import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='direct_logs',
                         exchange_type='direct')

severity = ['info', 'warning', 'error']
# 发送不同的routing_key
for i in range(20):
    message = '{} Hello World! {}'.format(i, severity[i % 3])
    channel.basic_publish(exchange='direct_logs',
                          routing_key=severity[i % 3],
                          body=message)
    print(" [x] Sent: {}".format(message))
connection.close()
  • 消费者 receiver.py
import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='direct_logs',
                         exchange_type='direct')

result = channel.queue_declare(queue='',exclusive=True)
queue_name = result.method.queue

channel.queue_bind(exchange='direct_logs',
                   queue=queue_name,
                   routing_key='info')

print(' [*] Waiting for logs. To exit press CTRL+C')

def callback(ch, method, properties, body):
    print(" [x] %r:%r" % (method.routing_key, body))

channel.basic_consume(callback,
                      queue=queue_name,
                      auto_ack=True)

channel.start_consuming()

最后根据不同的routing_key,接收任务

相关文章

网友评论

      本文标题:路由模式direct

      本文链接:https://www.haomeiwen.com/subject/oqhrfctx.html