使用 Spring AMQP 延迟消息发送到侦听器 [英] Delay message to send to listener using Spring AMQP
问题描述
我需要在一定时间后向 MessageListener 发送消息,那么有什么方法可以使用 Spring AMQP 来实现.
I have a requirement to send message to MessageListener after certain duration , So is there any way to achieve using Spring AMQP.
例如.生产者产生消息,消息进入 RabbitMQ Q ,消息被接收 Listener 立即收听 Q,我想延迟在消费者端接收消息,在一些配置参数后说 1000ms
Eg . Producer produces the message and message goes to RabbitMQ Q , The message gets received Listener listening to that Q immediately, I want to delay that message to be received at consumer side say after some configuration parameter say 1000ms
推荐答案
RabbitMQ 为此提供了延迟交换 功能.
The RabbitMQ provides for this purpose Delayed Exchange feature.
从 1.6 版开始,Spring AMQP 还提供了一个高级 API:http://docs.spring.io/spring-amqp/reference/html/_reference.html#delayed-message-exchange:
Starting with version 1.6 Spring AMQP also provides a high level API on the matter: http://docs.spring.io/spring-amqp/reference/html/_reference.html#delayed-message-exchange:
<rabbit:topic-exchange name="topic" delayed="true" />
<小时>
MessageProperties properties = new MessageProperties();
properties.setDelay(15000);
template.send(exchange, routingKey,
MessageBuilder.withBody("foo".getBytes()).andProperties(properties).build());
更新
在 Spring AMQP 1.6
之前你应该这样做:
Before Spring AMQP 1.6
you should do like this:
@Bean
CustomExchange delayExchange() {
Map<String, Object> args = new HashMap<String, Object>();
args.put("x-delayed-type", "direct");
return new CustomExchange("my-exchange", "x-delayed-message", true, false, args);
}
...
MessageProperties properties = new MessageProperties();
properties.setHeader("x-delay", 15000);
template.send(exchange, routingKey,
MessageBuilder.withBody("foo".getBytes()).andProperties(properties).build());
另请参阅此问题及其答案:Spring AMQP 中的调度/延迟消息传递RabbitMQ
Also see this question and its answer: Scheduled/Delay messaging in Spring AMQP RabbitMq
这篇关于使用 Spring AMQP 延迟消息发送到侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!