寫在前面,rabbitmq因為版本問題,傳入的參數的位置可能不同,可以查看源碼,一一對應進行傳入。
send.py
# encoding: utf-8
# Date: 2019/11/25 20:43
__author__ = 'ryan.liu'
import pika
def test(hash_value):
# 1, 連接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()
# 2,創建名為queue的隊列
channel.queue_declare(queue='queue')
# 3,配置basic_pulish
channel.basic_publish(
'',
'queue',
hash_value)
# 4,關閉連接
connection.close()
# return make_response({})
receive.py
# encoding: utf-8
# Date: 2019/11/25 20:43
__author__ = 'ryan.liu'
import pika
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()
# 聲明隊列
channel.queue_declare(queue='queue')
# 3,定義一個回調函數,當獲得消息時,Pika庫調用這個回調函數來處理消息
def callback(ch, method, properties, body):
print("receive.py: receive message", body)
# 4,從隊列接收消息
# channel.basic_consume(
# queue='queue',
# callback,
# no_ack=True)
channel.basic_consume(
"queue",
callback,
auto_ack=True
)
# 5,等待消息
channel.start_consuming()
今天犯了個錯,導致mq一直報錯,錯誤提示為:
OSError: [Errno 9] Bad file descriptor
錯誤代碼如下:
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()
channel.queue_declare(queue='queue')
def test(hash_value):
channel.basic_publish(
'',
'queue',
hash_value)
connection.close()
# return make_response({})
這是python基礎的作用域的問題。
rabbitmq報錯
pika.exceptions.IncompatibleProtocolError: StreamLostError: ('Transport indicated EOF',)
因為我是用docker起的rabbitMQ服務,我把端口映射到8181端口,但事實上docker啟動MQ的時候,會自動啟動5672端口,所以在配置的時候,port使用默認的即可,而不是8181。