因此,我开始使用RabbitMQ并在网站https://www.rabbitmq.com/tutorials/tutorial-one-javascript.html上进行了教程,但我没有100%理解如何设置知识功能,以便队列在发送消息后立即删除该消息,它消息是否被消耗都无关紧要。我正在尝试创建一个队列,该队列将在发送发生后立即删除所有消息
我尝试了Tutorials中的示例,例如hello world示例显示noAck属性设置为true,这意味着我们没有确认消息,因此Queue应该在发送完消息后实际上删除这些消息,但这不是情况是因为当我运行send.js 3次,然后运行receive.js时,我将收到3次Hello World消息,这不是我想要的
// this is send.js
var amqp = require('amqplib/callback_api');
amqp.connect('amqp://localhost', function(error0, connection) {
if (error0) {
throw error0;
}
connection.createChannel(function(error1, channel) {
if (error1) {
throw error1;
}
var queue = 'hello';
var msg = 'Hello World!';
channel.assertQueue(queue, {
durable: false
});
channel.sendToQueue(queue, Buffer.from(msg));
console.log(" [x] Sent %s", msg);
});
setTimeout(function() {
connection.close();
process.exit(0);
}, 500);
});
// this is receive .js
var amqp = require('amqplib/callback_api');
amqp.connect('amqp://localhost', function(error0, connection) {
if (error0) {
throw error0;
}
connection.createChannel(function(error1, channel) {
if (error1) {
throw error1;
}
var queue = 'hello';
channel.assertQueue(queue, {
durable: false
});
console.log(" [*] Waiting for messages in %s. To exit press CTRL+C",
queue);
channel.consume(queue, function(msg) {
console.log(" [x] Received %s", msg.content.toString());
}, {
noAck: true
});
});
});
例如,如果我运行3次send.js,则可能会发生2种情况。情况1是消息将从接收方使用并完成。 case2是不会从接收方使用它,在这种情况下,我希望将其删除,如果我从send.js运行一个月后运行receive.js,则不希望该消息被使用,但我也希望队列能够耐用且不排他。 当我继续调用send.js并且消息将一直被推送到该队列中时,这也是一个问题,然后如果我运行receive.js,我将同时收到1000条消息,因此我的目标是避免这种情况。 感谢您的帮助
答案 0 :(得分:0)
我认为,在再次阅读评论和问题后,您想要的是您希望将消息传递给消费者,还是希望暂时将其丢弃它进入队列。在这种情况下,您可以在队列或单个消息上将TTL设置为0。来自documentation的相关部分:
将TTL设置为0会导致消息在到达队列时过期,除非可以立即将其传递给使用者。
要设置队列的TTL,在使用JavaScript客户端的情况下,您需要修改对channel.assertQueue
的调用,以将arguments
设置为0的x-message-ttl
包括在内。这是示例相关部分:
var queue = 'hello';
channel.assertQueue(queue, {
durable: false,
arguments: {
"x-message-ttl": 0
}
});
有关更多详细信息,请咨询amqp.node
documentation。