一、消息发送端代码:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pika
import random
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
#创建一个通道
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange="",routing_key='hello',body='this is a mq test %d' % (random.randint(0,1000)))
print("[x]send this is a mq test")
connection.close()
二、消息接收端代码:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
#创建一个频道对象
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch,method,properties,body):
print('[x] Received msg:is %s' % body)
channel.basic_consume('hello',callback,True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()