写在前面,rabbitmq因为版本问题,传入的参数的位置可能不同,可以查看源码,一一对应进行传入。
send.py
# encoding: utf-8
# Date: 2019/11/25 20:43
__author__ = 'ryan.liu'
import pika
def test(hash_value):
# 第一步,连接RabbitMq服务器
rabbit_username = 'admin'
rabbit_password = 'admin'
credentials = pika.PlainCredentials(rabbit_username, rabbit_password)
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='127.0.0.1', port=5672, credentials=credentials))
# channel是进行消息读写的通道
channel = connection.channel()
# 第二步,创建一个名为queue的队列,然后把消息发送到这个队列
channel.queue_declare(queue='queue')
# 第三步,现在可以发送消息,但是RabbitMQ不能把消息直接发送到队列,要发送到交换器,这个稍后介绍,这里使用默认交换器(exchange),
# 它使用一个空字符串标识,routing_key参数必须指定为队列名称,这里为queue
channel.basic_publish(
'',
'queue',
hash_value)
# 退出程序前,通过关闭连接保证消息已经投递到RabbitMq
connection.close()
# return make_response({})
receive.py
# encoding: utf-8
# Date: 2019/11/25 20:43
__author__ = 'ryan.liu'
import pika
# 第一步,同样连接RabbitMq服务器
rabbit_username = 'admin'
rabbit_password = 'admin'
credentials = pika.PlainCredentials(rabbit_username, rabbit_password)
connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1', port=5672, credentials=credentials))
channel = connection.channel()
# 为确保队列存在,再次执行queue_declare创建一个队列,我们可以多次运行该命令,但是只有一个队列会创建
# 因为不能保证send.py先执行还是receive.py先执行,所以重复声明队列来确保其存在
channel.queue_declare(queue='queue')
# 第三步,定义一个回调函数,当获得消息时,Pika库调用这个回调函数来处理消息,该回调函数将消息内容打印到屏幕
def callback(ch, method, properties, body):
print("receive.py: Received message %r" % (body,))
# 第四步,告诉rabbbitMq回调函数将从queue队列接收消息
# channel.basic_consume(
# queue='queue',
# callback,
# no_ack=True)
channel.basic_consume(
"queue",
callback,
auto_ack=True
)
# 第五步,输入一个无限循环来等待消息数据并运行回调函数
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
今天犯了个错,导致mq一直报错,错误提示为:
OSError: [Errno 9] Bad file descriptor
错误代码如下:
# 第一步,连接RabbitMq服务器
rabbit_username = 'admin'
rabbit_password = 'admin'
credentials = pika.PlainCredentials(rabbit_username, rabbit_password)
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='127.0.0.1', port=5672, credentials=credentials))
# channel是进行消息读写的通道
channel = connection.channel()
# 第二步,创建一个名为queue的队列,然后把消息发送到这个队列
channel.queue_declare(queue='queue')
# 第三步,现在可以发送消息,但是RabbitMQ不能把消息直接发送到队列,要发送到交换器,这个稍后介绍,这里使用默认交换器(exchange),
# 它使用一个空字符串标识,routing_key参数必须指定为队列名称,这里为queue
def test(hash_value):
channel.basic_publish(
'',
'queue',
hash_value)
# 退出程序前,通过关闭连接保证消息已经投递到RabbitMq
connection.close()
# return make_response({})
这是python基础的作用域的问题。