我需要在一段时间后向MessageListener发送消息,那么有没有办法实现使用Spring AMQP。
例如。 生产者生成消息并将消息发送到RabbitMQ Q,消息收到监听器立即收听该Q,我想延迟消息在消费者端接收后说一些配置参数说1000ms
答案 0 :(得分:3)
RabbitMQ为此提供了Delayed Exchange功能。
从版本1.6开始,Spring AMQP还提供了关于此问题的高级API: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());
<强>更新强>
在春季AMQP 1.6
之前你应该这样做:
@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());
另请参阅此问题及其答案:Scheduled/Delay messaging in Spring AMQP RabbitMq
答案 1 :(得分:0)
如果使用Spring Boot,它可能是这样的:
@Bean
Queue queue() {
return QueueBuilder.durable(queueName)
.withArgument("x-dead-letter-exchange", dlx)
.withArgument("x-dead-letter-routing-key", dlq)
.build();
}
@Bean
TopicExchange exchange() {
return (TopicExchange) ExchangeBuilder.topicExchange(topicExchangeName)
.delayed()
.build();
@Bean
Binding binding() {
return BindingBuilder.bind(queue()).to(exchange()).with(queueName);
}