问 题
比如某个队列 'rpc_queue' 是以前由其他python脚本创建的持久化队列,在rabbitmq中一直存在着。
在某次写脚本时,也申明了一个同名的队列,但不是持久化的,就会报错。
如果直接删除再创建,当然可以,像这样:
channel.queue_delete(queue='rpc_queue')
channel.queue_declare(queue='rpc_queue')
但实际上,创建队列时并不能确定某队列是否已存在,如果用try的方式,像这样
try:
channel.queue_declare(queue='rpc_queue')
except:
channel.queue_delete(queue='rpc_queue')
channel.queue_declare(queue='rpc_queue')
也会报错。报错信息:
Traceback (most recent call last):
File "D:\rpc_server.py", line 11, in
channel.queue_declare(queue='rpc_queue')
File "D:\liuzhibo\Python35\lib\site-packages\pika\adapters\blocking_connection.py", line 2329, in queue_declare
self._flush_output(declare_ok_result.is_ready)
File "D:\liuzhibo\Python35\lib\site-packages\pika\adapters\blocking_connection.py", line 1181, in _flush_output
raise exceptions.ChannelClosed(method.reply_code, method.reply_text)
pika.exceptions.ChannelClosed: (406, "PRECONDITION_FAILED - inequivalent arg 'durable' for queue 'rpc_queue' in vhost '/': received 'false' but current is 'true'")
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\rpc_server.py", line 13, in
channel.queue_delete(queue='rpc_queue')
File "D:\liuzhibo\Python35\lib\site-packages\pika\adapters\blocking_connection.py", line 2351, in queue_delete
nowait=False)
File "D:\liuzhibo\Python35\lib\site-packages\pika\channel.py", line 717, in queue_delete
self._validate_channel_and_callback(callback)
File "D:\liuzhibo\Python35\lib\site-packages\pika\channel.py", line 1179, in _validate_channel_and_callback
raise exceptions.ChannelClosed()
pika.exceptions.ChannelClosed
channel对象下貌似也没有判断一个队列是否存在的方法,那要怎么样动态的判断一个队列是否存在并删除之?
解决方案
错误很明显嘛,重新拿 channel 就好了:
# -*- coding: utf-8 -*-
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='first', type='fanout')
#channel.queue_declare(queue='hello')
#channel.queue_delete(queue='hello')
#sys.exit(0)
try:
channel.queue_declare(queue='hello', durable=True)
except:
channel = connection.channel()
channel.queue_delete(queue='hello')
channel.queue_declare(queue='hello', durable=True)
channel.queue_bind(exchange='first', queue='hello')
channel.basic_publish(exchange='first', routing_key='', body='Hello World!')
扫一扫关注IT屋
微信公众号搜索 “ IT屋 ” ,选择关注与百万开发者在一起