1. 发布者
#coding:utf8 import pika import json import sys message = ''.join(sys.argv[1:]) or "hello word" connection = pika.BlockingConnection(pika.ConnectionParameters( 'localhost')) channel = connection.channel() channel.exchange_declare(exchange='logs', exchange_type='fanout') # 创建交换机 channel.basic_publish(exchange='logs', routing_key='', body=message) print " [x] Sent 'Hello World!'" connection.close()
2. 订阅者
# coding:utf8 import pika import MySQLdb import time connection = pika.BlockingConnection(pika.ConnectionParameters( 'localhost')) channel = connection.channel() channel.exchange_declare(exchange='logs',exchange_type='fanout') result = channel.queue_declare(exclusive=True) queue_name = result.method.queue channel.queue_bind(exchange='logs',queue=queue_name) def callback(ch, method, properties, body): print("[x] received %r" % body) time.sleep(5) print("done") # ch.basic_ack(delivery_tag=method.delivery_tag) # ack 消息成功确认 channel.basic_qos(prefetch_count=1)#公平分派 channel.basic_consume(callback, queue=queue_name, no_ack=True) print("waiting for messages") channel.start_consuming()