赞
踩
向Queue_TTL队列里发送消息,10秒后当消息没有被正常消费掉则消息过期被转发至 Queue_DLX死信队列
- const amqp = require('amqplib');
-
- async function TTL_production() {
- var conn = await amqp.connect("amqp://localhost:5672");
- var channel = await conn.createChannel();
- var Exchange_TTL = "Exchange_TTL";
- var Queue_TTL = "Queue_TTL";
- var RoutingKey_TTL = "RoutingKey_TTL";
- var Exchange_DLX = 'Exchange_DLX';
- var Queue_DLX = 'Queue_DLX';
- var RoutingKey_DLX = 'RoutingKey_DLX';
- //创建死信队列 这里声明死信队列是为了确保死信队列每次都存在,消息不会丢失
- await channel.assertExchange(Exchange_DLX, 'direct', { autoDelete: true, durable: true });
- await channel.assertQueue(Queue_DLX, {
- exclusive: false,
- });
- await channel.bindQueue(Queue_DLX, Exchange_DLX, RoutingKey_DLX)
- //创建消息队列
- await channel.assertExchange(Exchange_TTL, "direct", { autoDelete: true, durable: true });
- await channel.assertQueue(Queue_TTL, {
- exclusive: false,
- deadLetterExchange: Exchange_DLX,
- deadLetterRoutingKey: RoutingKey_DLX,
- });
- await channel.bindQueue(Queue_TTL, Exchange_TTL, RoutingKey_TTL);
- await channel.publish(Exchange_TTL, RoutingKey_TTL, Buffer.from("发送了一条消息!"), {
- //消息10秒后过期
- expiration: '10000'
- })
- console.log("消息发送成功");
- await channel.close();
- await conn.close();
- }
-
- TTL_production();
2. 死信消费者
- const amqp = require('amqplib');
-
- async function DLX_comsumer() {
- var conn = await amqp.connect("amqp://localhost:5672");
- var channel = await conn.createChannel();
- var Exchange_DLX = 'Exchange_DLX';
- var Queue_DLX = 'Queue_DLX';
- var RoutingKey_DLX = 'RoutingKey_DLX';
- await channel.assertExchange(Exchange_DLX, 'direct', { autoDelete: true, durable: true });
- await channel.assertQueue(Queue_DLX, {
- exclusive: false,
- });
- await channel.bindQueue(Queue_DLX, Exchange_DLX, RoutingKey_DLX)
- await channel.prefetch(1, false)
- await channel.consume(Queue_DLX, msg => {
- console.log(msg.content.toString())
- channel.ack(msg);
- }, { noAck: false })
- await channel.close();
- await conn.close();
- }
-
-
- DLX_comsumer();
执行生产者向Queue_TTL 发送消息。
10秒后消息会转发至Queue_DLX
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。