我正在尝试验证channel.consume
何时使用 Pika 0.11.2 从 RabbitMQ 服务器获取消息
当调用get_mq
和我检测到时:队列中的空消息发生异常。那么,我怎样才能使异常有效
这是我的代码:
def send_mq(self, message, queue_name):
try:
if message and queue_name:
message = json.dumps(message)
self.connect(queue_name)
self.channel.basic_publish(exchange="", routing_key=queue_name, body=message)
if self.mqConn:
self.mqConn.close()
except Exception as ex:
sentry_log('send_mq_error', str(ex))
def get_mq(self, callback, queue_name, limit_message=0):
if callback and queue_name:
self.connect(queue_name)
queue = self.channel.queue_declare(queue=queue_name, durable=True, exclusive=False, auto_delete=False)
# Enabled delivery confirmations
self.channel.confirm_delivery()
if queue and queue.method.message_count > 0:
# method_frame, header_frame, body = self.channel.basic_get(queue=queue_name)
# self.channel.basic_ack(delivery_tag=method_frame.delivery_tag)
# self.channel.basic_qos(prefetch_count=1)
# self.channel.basic_consume(lambda ch, method, properties, body: callback(json.loads(body) if body else body), queue=queue_name, no_ack=True)
# # # start consuming (blocks)
# try:
# self.channel.start_consuming()
# except KeyboardInterrupt:
# self.channel.stop_consuming()
try:
# Get ten messages and break out
for method_frame, properties, body in self.channel.consume(queue=queue_name, inactivity_timeout=1):
if body:
# Acknowledge the message
self.channel.basic_ack(method_frame.delivery_tag)
self.channel.basic_qos(prefetch_count=1)
# Escape out of the loop with limit messages
if limit_message > 0 and method_frame.delivery_tag == limit_message:
break
callback(json.loads(body))
else:
break
self.channel.cancel()
except Exception as ex:
self.channel.cancel()
if self.mqConn:
self.mqConn.close()
错误消息:
"Nonetype"对象不可迭代
RabbitMQ 团队监控rabbitmq-users
邮件列表,并且只偶尔回答 StackOverflow 上的问题。
您好,我是 Pika 的维护者之一。consume
方法可以返回 3 元组或 None
,因此您应该使用此注释中提供的方法进行处理。
此问题已在此拉取请求中得到解决,并将在下一版本的 Pika: https://github.com/pika/pika/pull/901 中提供