ustbwang 发表于 2017-12-9 12:32:28

python rabbitMQ 发送端和接收端广播模式。

  消费者模型:



import pika,time

consumer = pika.BlockingConnection\
   (pika.ConnectionParameters('localhost'))#创建socket连接
channel = consumer.channel()#创建管道
channel.exchange_declare(exchange='logs',exchange_type = 'fanout')
result = channel.queue_declare(exclusive=True)#exclusive排他,唯一的,自动删除连接。
queue_name = result.method.queue#创建一个随机的队列名称
print('queue_name',queue_name)#打印该队列名称

channel.queue_bind(exchange='logs',
                     queue = queue_name)
def backcall(ch,method,properties,body):#参数body是发送过来的消息。
   print(ch,method,properties)

   print(' Received %r'%body)
   ch.basic_ack(delivery_tag=method.delivery_tag)

channel.basic_consume(backcall,#回调函数。执行结束后立即执行另外一个函数返回给发送端是否执行完毕。
                     queue=queue_name,
                     #no_ack=True#不会告知服务端我是否收到消息。一般注释。
                        )#如果注释掉,对方没有收到消息的话不会将消息丢失,始终在队列里等待下次发送。
print('waiting for message To exit   press CTRL+C')
channel.start_consuming()#启动后进入死循环。一直等待消息。
  生产者模型:



import pika
connection = pika.BlockingConnection(
   pika.ConnectionParameters('localhost'))#建立一个最基本的socket
chanel = connection.channel()#声明一个管道
chanel.exchange_declare(exchange='logs',exchange_type='fanout')#生成转换器名字为logs并定义类型为fanout
chanel.basic_publish(exchange='logs',#转换器ex名字
                      routing_key='',
                      body ='HELLO WORD!',
                      )
print( '发出一个消息')
connection.close()#关闭
页: [1]
查看完整版本: python rabbitMQ 发送端和接收端广播模式。