一、新創建一個Exchanges
二、消息發佈端
#!/usr/bin/env python import time import pika import datetime import json def get_message(): # 產生消息入口處 for i in range(100): # 生成10條消息 message = json.dumps({'id': "psub_0000%s" % i, "amount": 100 * i, "name": "melon", "createtime": str(datetime.datetime.now())}) producer(message) time.sleep(1) def producer(message): connection = pika.BlockingConnection( pika.ConnectionParameters(virtual_host='/melon_demo', host='82.156.19.94', port=5672, credentials=pika.PlainCredentials('guest', 'guest'))) channel = connection.channel() channel.exchange_declare(exchange='fanout_logs', exchange_type='fanout', internal=False, durable=True) channel.basic_publish(exchange='fanout_logs', routing_key='', body=message) print(" [x] Sent %r" % message) connection.close() if __name__ == "__main__": get_message() # 程序執行入口
三、消息接收端
#!/usr/bin/env python import pika connection = pika.BlockingConnection(pika.ConnectionParameters(virtual_host='/melon_demo', host='82.156.19.94', port=5672, credentials=pika.PlainCredentials('guest', 'guest'))) channel = connection.channel() channel.exchange_declare(exchange='fanout_logs', exchange_type='fanout', internal=False, durable=True) result = channel.queue_declare(queue='', exclusive=True) queue_name = result.method.queue print('========queue_name=======',queue_name) channel.queue_bind(exchange='fanout_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(queue=queue_name, on_message_callback=callback, auto_ack=True) channel.start_consuming()
四、先運行接收端程序,再運行發佈端