前言
在实际工作中,我们往往要实现一些延迟通知的功能,比如订单未付款30分钟后自动取消、邮件半小时后发送等等。
通过RabbitMq实现延迟队列主要有两种方式:
- 添加rabbitmq_delayed_message_exchange插件
- 通过死信队列机制
本篇用的是第二种。
实现步骤
- 创建一条死信队列
- 创建一条没有消费者消费的队列,用于消息超时后发送到死信队列
- 定时发送消息,观察是否成功延迟消费
代码演示
package org.jz.rabbitmq.chapter3;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@Slf4j
@EnableScheduling
@SpringBootApplication
public class Chapter3Application {
@Autowired
RabbitTemplate rabbitTemplate;
public static void main(String[] args) {
SpringApplication.run(Chapter3Application.class, args);
}
@Bean
public org.springframework.amqp.core.Queue queue() {
org.springframework.amqp.core.Queue queue = QueueBuilder.durable("delay")
.withArgument("x-dead-letter-exchange", "dead.direct")
.withArgument("x-dead-letter-routing-key", "dead")
.withArgument("x-message-ttl", 5000) //设置消息存活时间为5s
.build();
return queue;
}
//创建并且监听一条死信队列
@RabbitListener(bindings = @QueueBinding(value = @Queue(value = "dead"),
exchange = @Exchange(name = "dead.direct"), key = "dead"))
public void listenDead(String str) {
log.info("延时五秒接收到的消息: {}", str);
}
//延时5秒防止queue没有初始化成功
@Scheduled(initialDelay = 6000, fixedRate = 6000)
public void sendDelay() {
log.info("发送一条消息");
rabbitTemplate.convertAndSend("delay", "hello");
}
}
结果输出
2019-11-16 07:51:13.421 INFO 41664 --- [ scheduling-1] o.j.r.chapter3.Chapter3Application : 发送一条消息
2019-11-16 07:51:18.483 INFO 41664 --- [ntContainer#0-1] o.j.r.chapter3.Chapter3Application : 延时五秒接收到的消息: hello
2019-11-16 07:51:19.421 INFO 41664 --- [ scheduling-1] o.j.r.chapter3.Chapter3Application : 发送一条消息
2019-11-16 07:51:24.453 INFO 41664 --- [ntContainer#0-1] o.j.r.chapter3.Chapter3Application : 延时五秒接收到的消息: hello