UP | HOME

发布模式

Table of Contents

Exchange

RabbitMQ中生产者只会把消息发送给exchange,再由exchange推送给队列

exchanges.png

Figure 1: exchanges

列出所有的Exchange

$ sudo rabbitmqctl list_exchanges
Listing exchanges ...
logs      fanout
amq.direct      direct
amq.topic       topic
amq.fanout      fanout
amq.headers     headers
...done.

类型

  • default:匿名xchange,根据对应的routing_key发送给相关的队列
  • fanout: 消息广播给所有的队列
  • direct:消息路由
  • topic:模式匹配

Publish

前面描述的工作队列只会把信息发送给一个消费者,而发布模式则是把信息广播给多个消费者

publish_subscribe.png

Figure 2: publish & subscribe

  • 声明fanout exchange
    channel.exchange_declare(exchange='logs',
                             type='fanout')
    
  • 生产者:发布fanout exchange
    channel.basic_publish(exchange='logs',
                          routing_key='',
                          body=message)
    
  • 消费者:创建临时队列,队列拥有随机名字,并且被消费后就删除
    #not provide a queue name while declaring
    result = channel.queue_declare(exclusive=True) #once disconnect consumer, delete the queue
    
  • 消费者:绑定exchange和queue

    bindings.png

    Figure 3: bindings

channel.queue_bind(exchange='logs',
                   queue=result.method.queue)

显示所有的绑定

$ rabbitmqctl list_bindings
Listing bindings ...
logs    exchange        amq.gen-JzTY20BRgKO-HjmUJj0wLg  queue           []
logs    exchange        amq.gen-vso0PVvyiRIL2WoV3i48Yg  queue           []
...done.

测试

启动一个消费者把日志记录到文件

$ python receive_logs.py > logs_from_rabbit.log

再启动一个消费者把日志打印到控制台

$ python receive_logs.py

发送一个日志给exchange,可以看到两个消费者都接收并处理了日志

$ python emit_log.py

Next:消息路由

Previous:工作队列

Home:目录