RabbitMQ:如果消费者永远消失了,是否删除队列?

RabbitMQ: Delete a queue if consumer is gone forever?

假设每个用户都有自己的队列。当用户离线时将消息放入队列,当他们重新连接时,他们会收到所有这些消息。

但是,如果客户离开并且再也没有回来(停止使用该服务)怎么办?如果一段时间内没有使用消息,RabbitMQ 是否有办法删除队列?消息可能会传入,但不会传出,因为客户端不再处于活动状态。我如何使用 amqp.node 插件处理这个问题?

貌似可以,但我自己没试过。参见:

https://www.rabbitmq.com/ttl.html

查看底部的队列 TTL。 "This controls for how long a queue can be unused before it is automatically deleted."

要查看示例用法,node-amqp 代码库中的此测试可能会鼓舞人心:

https://github.com/postwait/node-amqp/blob/f64704d3727266230901598e2daf0fa780766feb/test/test-queue-args.js#L8

Imagine each user has it's own queue. Messages are put in to the queue when the user is offline and when they reconnect, they receive all those messages.

这是一个普遍的想法,但是 one with unfortunate consequences, that you should avoid

正如我在那篇链接文章中所写:

You could potentially work around this by having a queue per user. You could set up your code so that the web server only subscribes to a queue for the user when that user is logged in and available.

This doesn’t solve the problem.

Now you have 30,000 messages distributed across 1,000 queues – a bad situation in itself. This requires RabbitMQ to persist the queues and the messages within the queues. And what happens when all 1,000 users log in to your system at the same time? Now your web server has 1,000 queue subscriptions to deal with.

当然,您可能会争辩说您不会有那么多用户。但情况变得更糟。在你的情况下,你将无法按照你想要的方式自动删除队列。

您可以将队列设置为在所有消费者断开连接后自动删除。但是保持队列需要每个用户队列有一个消费者,只要该用户存在,消费者就会一直连接。如果应用程序崩溃,队列及其所有消息都会消失。

TTL 只会做你想做的一部分。它将使队列中的消息生效,并且消息将在该超时后被删除......但它不会删除队列。

最终,您不想使用 RabbitMQ 执行此操作。

同样,来自 my article on the subject

Getting back to the original scenario, what should you do when the user is not online and you can’t send the message to them immediately?

Store the message in a database.

Add a field to the database record that says who this message belongs to. When the user reconnects later, query the database for any messages that this user needs to see and send them along at that time.

The full process started above, then becomes this:

  • User’s browser connects to SignalR/Socket.io/Pusher/websockets on web server
  • Web server checks a queue for updates that happen during a long running process
  • When a message for a logged in user comes in
    • If the user is logged in, broadcast the message through the websocket to the user
    • If the user is not logged in, store the message in a database
  • When the user logs in again, query the database and send all waiting messages

It’s what you would have done before the idea of a message queue came in to play, right? It should be what you would do now that you have a message queue, as well.