gpt4 book ai didi

python - 如何让 Rabbitmq 队列以存储转发模式运行?

转载 作者:行者123 更新时间:2023-12-01 05:04:24 26 4
gpt4 key购买 nike

我正在使用 Python Pika 客户端试验 Rabbit MQ。我想做的是让我的 AMQP 发送器在存储和转发模式下运行,即如果服务器或网络出现故障,能够开始排队消息,并在以后可靠地传递它们。我怎么做?我的 amqp-sender.py 代码如下:



import pika
import psutil
import time
import datetime
import log
import json
import logging
import uuid
from dateutil.tz import tzlocal

logging.basicConfig()
logger = log.setup_custom_logger('amqp_send', 'amqp_send.log')

connection = pika.BlockingConnection(pika.ConnectionParameters(host='54.191.161.213'))
channel = connection.channel()
channel.confirm_delivery()

channel.queue_declare(queue='ems.data')

def get_mac_address():
return ':'.join(['{:02x}'.format((uuid.getnode() >> i) & 0xff) for i in range(0,8*6,8)][::-1])

while True:
now = datetime.datetime.now(tzlocal())
timestamp = now.strftime('%Y-%m-%d %H:%M:%S.%f %z')
data = {
'timestamp':timestamp,
'systemId':get_mac_address(),
'cpuPct':psutil.cpu_percent(),
'memoryUsed':psutil.virtual_memory().used
}
msg=json.dumps(data)
delivered=channel.basic_publish(exchange='', routing_key='abc', body=msg, mandatory=True)
if delivered:
logger.info("delivered %s" % msg)
else:
logger.error('failed to deliver %s' % msg)
time.sleep(1)

connection.close()



最佳答案

您需要将channel.confirm_delivery()mandatory=True一起使用

confirm_delivery 将返回 bool 值,具体取决于 Rabbit 是否正确处理消息。

强制标志:

This flag tells the server how to react if a message cannot be routed to a queue. Specifically, if mandatory is set and after running the bindings the message was placed on zero queues then the message is returned to the sender (with a basic.return). If mandatory had not been set under the same circumstances the server would silently drop the message.

所以你会得到这样的东西:

channel.confirm_delivery()
delivered = channel.basic_publish(exchange='', routing_key='ems.data', body=msg, mandatory=True)
if not delivered:
# store message for later reprocessing

关于python - 如何让 Rabbitmq 队列以存储转发模式运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25345767/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com