spring boot rabbitmq 延时消费的简单实现
目录
实现一:TTL
设置队列过期时间实现延时消费
设置消息过期时间实现延时消费
实现二:插件实现
公司最近需要用到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 {//交换机用于重新分配队列@BeanDirectExchange exchange() {return new DirectExchange("exchange");}//用于延时消费的队列@Beanpublic Queue repeatTradeQueue() {Queue queue = new Queue("repeatTradeQueue",true,false,false);return queue; }//绑定交换机并指定routing key@Beanpublic Binding repeatTradeBinding() {return BindingBuilder.bind(repeatTradeQueue()).to(exchange()).with("repeatTradeQueue");}//配置死信队列@Beanpublic 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 {SpringApplication.run(Application.class, args);}
}
配置生产者,这里生产者需要指定前面配置了过期时间的队列deadLetterQueue
import java.time.LocalDateTime;import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;@Component
public class DeadLetterSender {@Autowiredprivate AmqpTemplate rabbitTemplate;public void send(String msg) {System.out.println("DeadLetterSender 发送时间:"+LocalDateTime.now().toString()+" msg内容:"+msg);rabbitTemplate.convertAndSend("deadLetterQueue", msg);}}
配置消费者,消费者监听指定用于延时消费的队列repeatTradeQueue
import java.time.LocalDateTime;@Component
@RabbitListener(queues = "repeatTradeQueue")
public class RepeatTradeReceiver {@RabbitHandlerpublic void process(String msg) {System.out.println("repeatTradeQueue 接收时间:"+LocalDateTime.now().toString()+" 接收内容:"+msg);}}
写一个简单的接口调用测试延时消费是否成功
import org.springframework.beans.factory.annotation.Autowired;@RestController
@RequestMapping("/rabbit")
public class RabbitTest {@Autowiredprivate DeadLetterSender deadLetterSender;@GetMapping("/deadTest")public void deadTest() {deadLetterSender.send("队列设置过期时间测试");}}
启动项目开始测试
发送端和接收端时间间隔3秒(毫秒差就不要较真了⊙﹏⊙|||)
设置消息过期时间实现延时消费
还是先贴上配置的代码,基本配置都一样,唯一的区别是deadLetterQueue的过期时间这里不做配置,需要注意的是,因为我这里用的是同一个队列名,所以即使将队列过期时间配置删除,mq中该队列过期时间仍然还是存在的,所以需要删除该队列,启动项目时才能重新配置该队列属性,可能可以通过配置的方式重新覆盖属性配置,小白没研究出来(ಥ_ಥ),当然也可以保留队列过期时间的配置,当两个过期时间都存在时,消息取更小的过期时间。
import java.util.HashMap;@SpringBootApplication
public class Application {//用于死信队列转发的交换机@BeanDirectExchange exchange() {return new DirectExchange("exchange");}//用于延时消费的队列@Beanpublic Queue repeatTradeQueue() {Queue queue = new Queue("repeatTradeQueue",true,false,false);return queue; }//绑定交换机并指定routing key@Beanpublic Binding repeatTradeBinding() {return BindingBuilder.bind(repeatTradeQueue()).to(exchange()).with("repeatTradeQueue");}//配置死信队列@Beanpublic Queue deadLetterQueue() {Map<String,Object> args = new HashMap<>();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 {SpringApplication.run(Application.class, args);}
}
配置生产者,message的expiration就是过期时间的设置,单位也是毫秒
import java.time.LocalDateTime;import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;@Component
public class DeadLetterSender {@Autowiredprivate AmqpTemplate rabbitTemplate;public void send(String msg, long times) {System.out.println("DeadLetterSender 发送时间:" + LocalDateTime.now().toString() + " msg内容:" + msg);MessagePostProcessor processor = new MessagePostProcessor() {@Overridepublic Message postProcessMessage(Message message) throws AmqpException {message.getMessageProperties().setExpiration(times + "");return message;}};rabbitTemplate.convertAndSend("deadLetterQueue", (Object)msg, processor);}
}
消费者不变,用之前的类即可
稍微修改一下接口,设置时间为5秒
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import me.miaobo.mq.sender.DeadLetterSender;@RestController
@RequestMapping("/rabbit")
public class RabbitTest {@Autowiredprivate DeadLetterSender deadLetterSender;@GetMapping("/deadTest")public void deadTest() {deadLetterSender.send("消息设置过期时间测试",5000);}
}
补充一下队列的删除,在控制台选择queues菜单,找到我们配置的队列,点击名称进详情,操作介绍有点傻,不清楚mq的可以看看之前的链接贴。
Mac 安装 rabbitmq
进入详情界面可以看到之前的配置,过期时间3秒,自己通过项目重启发现过期时间并不会删除,只好在管理界面手动删除。
下拉详情页面,找到删除按钮,删除该队列
启动服务,测试接口
时间相隔5秒,和接口设置的时间保持一致。
为了验证队列和消息过期时间同时配置时取最小值,我又删除了队列一遍,把队列3秒过期时间加上。
继续测试 (●゚ω゚●),还是用之前的接口测试。
不再是接口设置的5秒过期时间,而是队列设置的3秒过期时间生效。
实现二:插件实现
rabbitmq 安装rabbitmq_delayed_message_exchange插件(版本要求网上说3.5.7以上,未验证低版本问题,安装的3.7.7版本)
插件下载地址
插件包放在rabbit安装目录/plugins/菜单下
运行命令
rabbitmq-plugins enable rabbitmq_delayed_message_exchange
安装Erlang(版本要求网上说18.0以上,未验证低版本问题,homebrew自动安装的20.3.8.2版本)
mac通过brew命令安装
brew install erlang
windows的没研究,可以自己百度下(~ ̄▽ ̄)~
插件实现延时消费时踩了个坑,就是插件包版本有问题,自己在网上下载别人分享的包,结果测试一直不通过,折腾了挺久没找到原因,怀疑是插件包的问题,就去官网下载了对应3.7.7版本的插件包。
安装完成后去管理页面验证插件是否有效
插件若安装成功,type类型会有多一个x-delayed-message,rabbitmq默认是没有的,add一个exchange,选择该类型,添加成功说明插件启用成功。我是没测试add,结果直接去写demo测试了,结果一直启动报错还不知道原因,后来发现是插件包的问题/(ㄒoㄒ)/~~。
接着就是延时队列的配置
注意delayedExchange是用的自定义类型,类型为x-delayed-message,x-delayed-type要求是rabbitmq的类型,取direct,topic,fanout,headers类型中的一个,x-delayed-type说实话不知道具体干嘛用的,就这么照着配置了 ( ̄3 ̄)。
import java.util.HashMap;@SpringBootApplication
public class Application {/*** 自定义的交换机类型* @return*/@BeanCustomExchange delayedExchange() {Map<String,Object> args = new HashMap<>();args.put("x-delayed-type", "direct");return new CustomExchange("delayedExchange","x-delayed-message",true,false,args);}/*** 创建一个队列* @return*/@Beanpublic Queue delayedQueue() {return new Queue("delayedQueue",true);}/** * 绑定队列到自定义交换机 * @return */ @Bean public Binding bindingNotify() { return BindingBuilder.bind(delayedQueue()).to(delayedExchange()).with("delayedQueue").noargs(); } public static void main(String[] args) throws Exception {SpringApplication.run(Application.class, args);}
}
配置生产者,这里对message的header信息进行配置,配置的x-delay参数就是延时时间,单位也是毫秒,指定绑定的交换机名称以及routing key
import java.time.LocalDateTime;import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;@Component
public class DelayedSender {@Autowiredprivate AmqpTemplate rabbitTemplate;public void send(String msg, long time) {System.out.println("DelayedSender 发送时间: " + LocalDateTime.now() + " msg内容:" + msg);MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {@Overridepublic Message postProcessMessage(Message message) throws AmqpException {message.getMessageProperties().setHeader("x-delay", time);return message;}};this.rabbitTemplate.convertAndSend("delayedExchange", "delayedQueue", msg, messagePostProcessor);}}
配置消费者,监听对应的队列名称delayedQueue
import java.time.LocalDateTime;import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;@Component
@RabbitListener(queues = "delayedQueue")
public class DelayedReceiver {@RabbitHandlerpublic void process(String msg) {System.out.println("DelayedReceiver 接受时间: " + LocalDateTime.now() + " msg内容:" + msg);}
}
写接口测试
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import me.miaobo.mq.sender.DelayedSender;@RestController
@RequestMapping("/rabbit")
public class RabbitTest {@Autowiredprivate DelayedSender delayedSender;@GetMapping("/delayedTest")public void delayedTest() {delayedSender.send("插件实现延时队列",6000);}}
启动项目测试,延迟时间为接口设置的6秒。
以上为自己对mq延时消费机制的简单实现,分享给初学mq的程序猿们,学习记录,仅供参考,欢迎评论区补充指点!
spring boot rabbitmq 延时消费的简单实现相关推荐
- spring boot + rabbitMq整合之死信队列(DL)
rabbit mq 死信队列 什么是死信队列? DL-Dead Letter 死信队列 死信,在官网中对应的单词为"Dead Letter",可以看出翻译确实非常的简单粗暴.那么死 ...
- Spring boot Rabbitmq 示例
Spring boot Rabbitmq 示例 简介 Spring boot RabbitMQ 简单程序示例 编写详情 RabbitMQ docker 避免麻烦,直接使用docker启 ...
- Spring Boot 之路(一):一个简单的Spring Boot应用
SpringBoot之路(-) 一直在用Springboot做项目,但是像是赶鸭子上架一样,并没有系统的从头到一个项目来创建一个应用,最近打算做一个SpringBoot开箱即用的项目,主要是觉得自己很 ...
- Eclipse中spring boot的安装和创建简单的Web应用
1.添加STS插件 方法一 1.Help -> Eclipse Marketplace- 2.选择"Popular"标签去查找Spring Tool Suite (STS) ...
- 基于spring boot 的ssm项目的简单配置
2019独角兽企业重金招聘Python工程师标准>>> 我前面的帖子有介绍spring boot的简单搭建,现在我再讲讲spring boot的简单配置 首先,项目结构 启动类 @R ...
- Spring boot jar 项目,最简单的 pom 依赖引入
就像要一个超简单的spring boot 的jar项目的 pom文件的依赖的最简单的引入.引入最基础的依赖,能运行就行. pom文件: <?xml version="1.0" ...
- Spring boot + RabbitMQ延迟队列实战
一.背景 延时队列顾名思义,即放置在该队列里面的消息是不需要立即消费的,而是等待一段时间之后取出消费. 那么,为什么需要延迟消费呢?我们来看以下的场景: 订单业务: 在电商/点餐中,都有下单后 30 ...
- Spring Boot——RabbitMQ
转载自https://blog.csdn.net/lyhkmm/article/details/78772919 RabbitMq的介绍 RabbitMq的基本原理可以自行上网查阅,或者点击传送门:R ...
- Spring boot 之 dubbo 无xml 简单入门
Dubbo简介 Dubbo框架设计一共划分了10个层,而最上面的Service层是留给实际想要使用Dubbo开发分布式服务的开发者实现业务逻辑的接口层.图中左边淡蓝背景的为服务消费方使用的接口,右边淡 ...
最新文章
- mask rcnn网络结构笔记
- Android之利用ColorMatrix进行图片的各种特效处理
- Aspose Cell设置Excel单元格背景色
- webpack4.x开发环境配置
- 【话题】产品经理如何排期rd任务,才能更好控制产品节奏
- EOS声称的每秒百万级的交易速度靠谱么?
- C++判断是否为素数、求一个数的因数、质因数分解
- 关于bc中小数点length,scale,(())以及进制转换
- 研究生夏令营计算机题目,2017计算机学科夏令营上机考试-B编码字符串
- jQuery插件之:对话框
- oracle11g分区表维护,Oracle11g维护分区(一)AddingPartitions
- selenium简介_什么是Selenium? Selenium简介
- 高等数学复习笔记(一)- 高等数学基础知识、数列与函数的极限
- C++、QT的物业管理系统
- 使用Python+TensorFlow2构建基于卷积神经网络(CNN)的ECG心电信号识别分类(二)
- windows无法打开添加打印机_PDF-XChange Lite(pdf虚拟打印机)正式版下载-PDF-XChange Lite(pdf虚拟打印机)v8.0.342.0最新版下载...
- H桥电机驱动基本原理
- [转]Windows服务“允许服务与桌面交互”的使用和修改方法
- iperf3带宽测试工具
- -bash: vim: 未找到命令