生产者
mport pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1')) # 建立一个实例
channel = connection.channel() # 声明一个管道
channel.queue_declare(queue='hello ') # 声明一个queue
channel.basic_publish(exchange='',
routing_key='hello', # queue名字
body='hello word' # 消息内容
)
print("[x] sent 'hello word!'")
connection.close()
消费者
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1')) # 建立一个实例
channel = connection.channel() # 声明一个管道
channel.queue_declare(queue='hello') # 声明一个queue
def callback(ch, methon, properties, body): # ch 表示channel的内存地址
print('0000', ch, methon)
print("[x] Received %r", body)
channel.basic_consume(# 开始消费消息
'hello', # 队列名
callback , # 收到消息就调用callback来接收消息
auto_ack=True)
print('[*] waiting for message')
channel.start_consuming()