您的位置:首页 > 编程语言 > Python开发

Python RabbitMQ fanout

2017-05-28 10:45 357 查看
#########################消费者################################
#!/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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python rabbitmq fanout