且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

RabbitMQ 中的延迟消息

更新时间:2023-02-16 14:33:21

您可以尝试两种方法:

旧方法: 在每个消息/队列(策略)中设置 TTL(生存时间)标头,然后引入一个 DLQ 来处理它.一旦 ttl 过期,您的消息将从 DLQ 移动到主队列,以便您的侦听器可以处理它.

Old Approach: Set the TTL(time to live) header in each message/queue(policy) and then introduce a DLQ to handle it. once the ttl expired your messages will move from DLQ to main queue so that your listener can process it.

最新方法:最近 RabbitMQ 提出了 RabbitMQ Delayed Message Plugin ,使用它您可以实现相同的功能,并且该插件支持自 RabbitMQ-3.5.8 起可用.

Latest Approach: Recently RabbitMQ came up with RabbitMQ Delayed Message Plugin , using which you can achieve the same and this plugin support available since RabbitMQ-3.5.8.

您可以声明一个类型为 x-delayed-message 的交换,然后使用自定义标头 x-delay 发布消息,以毫秒为单位表示消息的延迟时间.消息将在 x-delay 毫秒

You can declare an exchange with the type x-delayed-message and then publish messages with the custom header x-delay expressing in milliseconds a delay time for the message. The message will be delivered to the respective queues after x-delay milliseconds

byte[] messageBodyBytes = "delayed payload".getBytes("UTF-8");
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("x-delay", 5000);
AMQP.BasicProperties.Builder props = new 
AMQP.BasicProperties.Builder().headers(headers);
channel.basicPublish("my-exchange", "", props.build(), messageBodyBytes);

更多信息:git