码迷,mamicode.com
首页 > 编程语言 > 详细

Python RabbitMQ fanout

时间:2017-05-28 16:05:02      阅读:338      评论:0      收藏:0      [点我收藏+]

标签:python   rabbitmq   fanout   

#########################消费者################################
#!/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

标签:python   rabbitmq   fanout   

原文地址:http://90sirdb.blog.51cto.com/8713279/1930421

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!