UP | HOME

消息路由

Table of Contents

消息路由

很多时候某个消费者只应该接受某些消息,对于这种情况广播就不适用,最简单的消息路由是direct exchange

Binding Key

可以额外传递参数routing_key给binding,为了与队列的routing_key区分,这个参数被称为binding key

channel.queue_bind(exchange=exchange_name,
                   queue=queue_name,
                   routing_key='black')

Direct Exchange

对于fanout exchange来说,binding key毫无意义,但对于direct exchange来说,只有当队列的routing_key与exchange的binding key相同的时候,exchange才会把消息推送给这个队列

direct-exchange.png

Figure 1: direct exchanges

多重Binding 

可以把一个direct exchange绑定到多个具有相同routing key的队列上

direct-exchange-multiple.png

Figure 2: multiple binding

根据日志级别做路由

route.png

Figure 3: route by log serverity

  • 生产者创建direct exchange
    channel.exchange_declare(exchange='direct_logs',
                             type='direct')
    
  • 生产者根据日志级别发送给不同的队列,队列的routing key就是日志级别
    channel.basic_publish(exchange='direct_logs',
                          routing_key=severity,
                          body=message)
    
  • 消费者为每个日志级别分别建立一个binding
    result = channel.queue_declare(exclusive=True)
    queue_name = result.method.queue
    
    for severity in severities:
        channel.queue_bind(exchange='direct_logs',
                           queue=queue_name,
                           routing_key=severity)
    

测试

启动一个消费者只接受warning和error级别日志到文件

$ python receive_logs_direct.py warning error > logs_from_rabbit.log

启动另外一个消费者接受所有级别日志,并打印到终端

$ python receive_logs_direct.py info warning error
 [*] Waiting for logs. To exit press CTRL+C

生产一条error级别的日志

$ python emit_log_direct.py error "Run. Run. Or it will explode."
[x] Sent 'error':'Run. Run. Or it will explode.'

Next:订阅话题

Previous:发布模式

Home:目录