生产者负责发送消息
# 生产者
import pika
import sys
username = 'guest'
pwd = 'guest'
user_pwd = pika.PlainCredentials(username, pwd)
s_conn = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
chan = s_conn.channel()
chan.queue_declare(queue='hello')
chan.basic_publish(exchange='', routing_key='hello', body='你好啊,兄弟!')
print('生产者 send 你好, 兄弟!')
s_conn.close()
消费者负责接收消息
import pika
username = 'guest'
pwd = 'guest'
user_pwd = pika.PlainCredentials(username, pwd)
s_conn = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
chan = s_conn.channel()
chan.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print("[消费者] recv %s" % str(body, encoding='UTF-8'))
chan.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)
print('[消费者] waiting for msg .')
chan.start_consuming()#开始循环取消息