RabbitMQ死信队列解决订单未支付取消代码
以下是一个示例RabbitMQ死信队列解决订单未支付取消的代码:
- 创建普通队列和死信队列
import pika
# 建立连接
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
# 创建普通队列
channel.queue_declare(queue='order_queue', durable=True, arguments={
'x-dead-letter-exchange': 'order_cancel_exchange', # 设置死信队列
'x-dead-letter-routing-key': 'order_cancel', # 设置死信队列路由键
})
# 创建死信队列
channel.exchange_declare(exchange='order_cancel_exchange', exchange_type='direct')
channel.queue_declare(queue='order_cancel', durable=True)
channel.queue_bind(queue='order_cancel', exchange='order_cancel_exchange', routing_key='order_cancel')
- 发送订单消息到队列
import json
# 发送订单消息
def send_order(order):
message = json.dumps(order)
channel.basic_publish(exchange='',
routing_key='order_queue',
body=message,
properties=pika.BasicProperties(
delivery_mode=2, # 消息持久化
))
- 消费订单消息并设置超时时间
import time
# 消费订单消息
def consume_order():
def callback(ch, method, properties, body):
order = json.loads(body)
print("Received order:", order)
# 设置订单超时时间为5秒
ch.basic_publish(exchange='',
routing_key='order_queue',
body=body,
properties=pika.BasicProperties(
delivery_mode=2,
expiration='5000' # 设置订单超时时间
))
channel.basic_consume(queue='order_queue', on_message_callback=callback, auto_ack=True)
print('Waiting for orders...')
channel.start_consuming()
- 消费死信队列并取消订单
# 消费死信队列
def consume_order_cancel():
def callback(ch, method, properties, body):
order = json.loads(body)
print("Cancel order:", order)
# 取消订单
# ...
channel.basic_consume(queue='order_cancel', on_message_callback=callback, auto_ack=True)
print('Waiting for cancel orders...')
channel.start_consuming()
- 启动消费者
if __name__ == '__main__':
# 启动消费订单消息
consume_order()
# 启动消费死信队列
consume_order_cancel()
当订单超时未支付时,会将订单消息发送到死信队列,并在死信队列中消费并取消订单。这样可以避免订单未支付而被系统误判为已付款的情况
原文地址: https://www.cveoy.top/t/topic/fJKJ 著作权归作者所有。请勿转载和采集!