1. 報錯信息如下:
File "C:\projects\project_name\mq\rabbitclient.py", line 26, in __init__
self.channel.queue_declare(queue=conf.queue_name)
File "C:\env\project_name\lib\site-packages\pika\adapters\blocking_connection.py", line 2507, in queue_declare
self._flush_output(declare_ok_result.is_ready)
File "C:\env\project_name\lib\site-packages\pika\adapters\blocking_connection.py", line 1340, in _flush_output
raise self._closing_reason # pylint: disable=E0702
pika.exceptions.ChannelClosedByBroker: (406, "PRECONDITION_FAILED - parameters for queue 'test_queue' in vhost '/test' not equivalent")
2. 代碼如下:
# -*- coding: utf-8 -*-
import json
import pika
import Config
class RabbitMQClient(object):
"""
RabbitMQ Client
"""
def __init__(self):
conf = Config()
credentials = pika.PlainCredentials(conf.rabbit_user, conf.rabbit_password)
self.conn = pika.BlockingConnection(pika.ConnectionParameters(
host=conf.rabbit_ip,
port=conf.rabbit_port,
virtual_host=conf.vhost,
credentials=credentials
))
self.channel = self.conn.channel()
self.exchange = conf.exchange
self.routing_key = conf.routing_key
self.channel.exchange_declare(exchange=self.exchange, exchange_type='direct', durable=True)
self.channel.queue_declare(queue=conf.queue_name)
self.channel.queue_bind(
queue=conf.queue_name,
exchange=self.exchange,
routing_key=self.routing_key
)
def send(self, msg):
try:
self.channel.basic_publish(
exchange=self.exchange,
routing_key=self.routing_key,
body=json.dumps(msg),
properties=pika.BasicProperties(
delivery_mode=2
)
)
except Exception as e:
raise e
def close(self):
self.conn.close()
if __name__ == '__main__':
client = RabbitMQClient()
client.send(exec_info)
client.close()
3. 定位問題
我們在聲明exchange的時候加了如下參數:durable=True,代表持久化;
發布信息的時候加了如下參數:delivery_mode=2,代表持久化消息;
我們再看聲明queue的時候如何?
在rabbitmq中,想要重啟后不丟失消息,要為信息加delivery_mode=2參數,只為消息加持久化限制,MQ重啟之后,exchange和queue全部丟失,也是不行的,所以也要為exchange和queue做持久化,都是由durable=True控制。
所以,修改上述代碼第26行如下:
self.channel.queue_declare(queue=conf.queue_name, durable=True)
再次測試便不報錯了。
