#########################消费者################################
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: Changhua Gong
import pika
'''
fanout模式:类似收音机的广播模式,
接收者(消费者)在的话,则接收;接收者不在的话,消息错过了就没有了。
'''
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs', # 和生产者对绑定
type='fanout')
# 声明对应queue,生产者不需声明
# 不指定queue名字,rabbit会随机分配一个名字,exclusive=True会在使用此queue的消费者断开后,自动将queue删除
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
channel.queue_bind(exchange='logs',
queue=queue_name)
print(' [*] Waiting for logs. To exit press CTRL+C')
def callback(ch, method, properties, body):
print(" [x] %r" % body)
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming()
#########################生产者################################
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: Changhua Gong
import pika
import sys
'''
fanout: 所有bind到此exchange的queue都可以接收消息
'''
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
# 生产者不需要声明queue
channel.exchange_declare(exchange='logs', # 指定exchanger的名字,随意
type='fanout') # 类型需指定fanout
message = ' '.join(sys.argv[1:]) or "info: Hello World!" # 默认输出参数,否则。。。
channel.basic_publish(exchange='logs',
routing_key='', # 不需指定具体的routing_key,但是要写
body=message)
print(" [x] Sent %r" % message)
connection.close()
转载于:https://blog.51cto.com/90sirdb/1930421