目录
公司最近需要用到rabbitmq,考虑到业务需求,后期可能需要用到mq延时消费机制。工作一年,对很多技术都不了解,还是一名技术小白,决定主动学习研究一下。
在网上查阅浏览了许多帖子,关于延时消费主要分为两种实现,一种是rabbitmq的TTL机制,一种是rabbitmq的插件实现。
感谢以下楼主的经验分享:
https://www.cnblogs.com/boshen-hzb/p/6841982.html springboot和rabbitmq整合
https://blog.csdn.net/u014308482/article/details/53036770 延时消费的两种实现
https://blog.csdn.net/u010046908/article/details/54773323 mac安装rabbitmq
以下为自己根据网上资料学习后得出的个人总结,如有错误之处,欢迎指正。
实现一:TTL
TTL指过期时间,rabbitmq可以通过设置队列的过期时间或者消息的过期时间实现延时消费。
准备工作:
安装rabbitmq
添加相关maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
设置队列过期时间实现延时消费
交换机及队列配置,公司用的spring-boot框架,为简化步骤,我直接配在启动类。
代码中有四个配置,第一个配置的exchange是用来接收已过期的队列信息并进行重新分配队列进行消费,第二个配置的repeatTradeQueue为exchange重新分配的队列名,第三个是将repeatTradeQueue队列与exchange交换机绑定,并指定对应的routing key,第四个配置的就是我们要设置过期时间的队列deadLetterQueue,配置中有三个参数,x-message-ttl为过期时间,该队列所有消息的过期时间都为我们配置的这个值,单位为毫秒,这里我设置过期时间为3秒,x-dead-letter-exchange是指过期消息重新转发到指定交换机,也就是exchange,x-dead-letter-routing-key是该交换机上绑定的routing-key,将通过配置的routing-key分配对应的队列,也就是前面配置的repeatTradeQueue。
import java.util.HashMap;
import java.util.Map;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Application {
//交换机用于重新分配队列
@Bean
DirectExchange exchange() {
return new DirectExchange("exchange");
}
//用于延时消费的队列
@Bean
public Queue repeatTradeQueue() {
Queue queue = new Queue("repeatTradeQueue",true,false,false);
return queue;
}
//绑定交换机并指定routing key
@Bean
public Binding repeatTradeBinding() {
return BindingBuilder.bind(repeatTradeQueue()).to(exchange()).with("repeatTradeQueue");
}
//配置死信队列
@Bean
public Queue deadLetterQueue() {
Map<String,Object> args = new HashMap<>();
args.put("x-message-ttl", 3000);
args.put("x-dead-letter-exchange", "exchange");
args.put("x-dead-letter-routing-key", "repeatTradeQueue");
return new Queue("deadLetterQueue", true, false, false, args);
}
public static void main(String[] args) throws Exception {