发布订阅

  消息传达给多个消费者,这里构建一个日志记录系统

  RabbitMQ消息传递模型思想:生产者只能将消息发送到转发器,转发器做的就是接收生产者发来的消息,另外方面就是把消息推送到队列中。

交换类型

  direct:通过routingKey和exchange决定的哪一组的queue可以接收消息

  topic:所有符合routingKey(此时可以是一个表达式)的routingKey所bind的queue可以接收消息

  headers:通过headers 来决定把消息发给哪些queue

  fanout:所有bind到此exchange的queue都可以接收消息

publisher.py

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3
 4 import pika
 5 import sys
 6
 7 credentials = pika.PlainCredentials('admin', 'admin123456')
 8 connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.1.6', credentials=credentials))
 9 channel = connection.channel()
10
11 channel.exchange_declare(exchange='logs', exchange_type='fanout')
12
13 message = ' '.join(sys.argv[1:]) or "info: Hello World!"
14 channel.basic_publish(exchange='logs', routing_key='', body=message)
15 print(" [x] Sent %r" % message)
16 connection.close()

 subscriber.py

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3
 4 import pika
 5
 6 credentials = pika.PlainCredentials('admin', 'admin123456')
 7 connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.1.6', credentials=credentials))
 8 channel = connection.channel()
 9 # 申明交换器和类型
10 channel.exchange_declare(exchange='logs', exchange_type='fanout')
11 # 无论何时连接RabbitMQ需要一个空的队列,queue=''随机创一个空队列,一旦接收方连接关闭,就会自动删除队列
12 result = channel.queue_declare(queue='', exclusive=True)
13 # 包含一个随机队列名称 比如:amq.gen-JzTY20BRgKO-HjmUJj0wLg
14 queue_name = result.method.queue
15 # 要告诉转发器发送到哪个队列,这里转发器和队列之间就要建立绑定关系
16 # 注意如果没有队列绑定到交换器上消息将会丢失
17 channel.queue_bind(exchange='logs', queue=queue_name)
18
19 print(' [*] Waiting for logs. To exit press CTRL+C')
20
21
22 def callback(ch, method, properties, body):
23     print(" [x] %r" % body)
24
25
26 channel.basic_consume(
27     queue=queue_name, on_message_callback=callback, auto_ack=True)
28
29 channel.start_consuming()

运行结果(注意这里实时性,就是订阅方没启动,此时订阅方是收不到发布方的消息的)

02-12 11:31