Spring Boot RabbitMQ 延遲消息實(shí)現(xiàn)完整版示例
概述
曾經(jīng)去網(wǎng)易面試的時(shí)候,面試官問(wèn)了我一個(gè)問(wèn)題,說(shuō)
下完訂單后,如果用戶未支付,需要取消訂單,可以怎么做
我當(dāng)時(shí)的回答是,用定時(shí)任務(wù)掃描DB表即可。面試官不是很滿意,提出:
用定時(shí)任務(wù)無(wú)法做到準(zhǔn)實(shí)時(shí)通知,有沒(méi)有其他辦法?
我當(dāng)時(shí)的回答是:
可以用隊(duì)列,訂單下完后,發(fā)送一個(gè)消息到隊(duì)列里,并指定過(guò)期時(shí)間,時(shí)間一到,執(zhí)行回調(diào)接口。
面試官聽(tīng)完后,就不再問(wèn)了。其實(shí)我當(dāng)時(shí)的思路是對(duì)的,只不過(guò)講的不是很專業(yè)而已。專業(yè)說(shuō)法是利用 延遲消息 。
其實(shí)用定時(shí)任務(wù),確實(shí)有點(diǎn)問(wèn)題,原本業(yè)務(wù)系統(tǒng)希望10分鐘后,如果訂單未支付,就馬上取消訂單,并釋放商品庫(kù)存。但是一旦數(shù)據(jù)量大的話,就會(huì)加長(zhǎng)獲取未支付訂單數(shù)據(jù)的時(shí)間,部分訂單就做不到10分鐘后取消了,可能是15分鐘,20分鐘之類的。這樣的話,庫(kù)存就無(wú)法及時(shí)得到釋放,也就會(huì)影響成單數(shù)。而利用延遲消息,則理論上是可以做到按照設(shè)定的時(shí)間,進(jìn)行訂單取消操作的。
目前網(wǎng)上關(guān)于使用RabbitMQ實(shí)現(xiàn)延遲消息的文章,大多都是講如何利用RabbitMQ的死信隊(duì)列來(lái)實(shí)現(xiàn),實(shí)現(xiàn)方案看起來(lái)都很繁瑣復(fù)雜,并且還是使用原始的RabbitMQ Client API來(lái)實(shí)現(xiàn)的,更加顯得啰嗦。
Spring Boot 已經(jīng)對(duì)RabbitMQ Client API進(jìn)行了包裝,使用起來(lái)簡(jiǎn)潔很多,下面詳細(xì)介紹一下如何利用 rabbitmq_delayed_message_exchange 插件和Spring Boot來(lái)實(shí)現(xiàn)延遲消息。
軟件準(zhǔn)備
erlang
本文使用的版本是:Erlang 20.3
RabbitMQ
本文使用的是 window 版本的RabbitMQ,版本號(hào)是:3.7.4
rabbitmq_delayed_message_exchange插件
插件下載地址:http://www.rabbitmq.com/community-plugins.html
打開(kāi)網(wǎng)址后,ctrl + f,搜索 rabbitmq_delayed_message_exchange 。
千萬(wàn)記住,一定選好版本號(hào),由于我使用的是RabbitMQ 3.7.4,因此對(duì)應(yīng)的 rabbitmq_delayed_message_exchange 插件也必須選擇3.7.x的。
如果沒(méi)有選對(duì)版本,在使用延遲消息的時(shí)候,會(huì)遇到各種各樣的奇葩問(wèn)題,而且網(wǎng)上還找不到解決方案。我因?yàn)檫@個(gè)問(wèn)題,折騰了整整一個(gè)晚上。請(qǐng)牢記,要選對(duì)插件版本。
下載完插件后,將其放置到RabbitMQ安裝目錄下的 plugins 目錄下,并使用如下命令啟動(dòng)這個(gè)插件:
rabbitmq-plugins enable rabbitmq_delayed_message_exchange
如果啟動(dòng)成功會(huì)出現(xiàn)如下信息:
The following plugins have been enabled: rabbitmq_delayed_message_exchange
啟動(dòng)插件成功后,記得重啟一下RabbitMQ,讓其生效。
集成RabbitMQ
這個(gè)就非常簡(jiǎn)單了,直接在maven工程的pom.xml文件中加入
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
Spring Boot的版本我使用的是 2.0.1.RELEASE .
接下來(lái)在 application.properties 文件中加入redis配置:
spring.rabbitmq.host=127.0.0.1 spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest
定義ConnectionFactory和RabbitTemplate
也很簡(jiǎn)單,代碼如下:
package com.mq.rabbitmq; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @ConfigurationProperties(prefix = "spring.rabbitmq") public class RabbitMqConfig { private String host; private int port; private String userName; private String password; @Bean public ConnectionFactory connectionFactory() { CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(host,port); cachingConnectionFactory.setUsername(userName); cachingConnectionFactory.setPassword(password); cachingConnectionFactory.setVirtualHost("/"); cachingConnectionFactory.setPublisherConfirms(true); return cachingConnectionFactory; } @Bean public RabbitTemplate rabbitTemplate() { RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory()); return rabbitTemplate; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
Exchange和Queue配置
package com.mq.rabbitmq; import org.springframework.amqp.core.*; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.HashMap; import java.util.Map; @Configuration public class QueueConfig { @Bean public CustomExchange delayExchange() { Map<String, Object> args = new HashMap<>(); args.put("x-delayed-type", "direct"); return new CustomExchange("test_exchange", "x-delayed-message",true, false,args); } @Bean public Queue queue() { Queue queue = new Queue("test_queue_1", true); return queue; } @Bean public Binding binding() { return BindingBuilder.bind(queue()).to(delayExchange()).with("test_queue_1").noargs(); } }
這里要特別注意的是,使用的是 CustomExchange ,不是 DirectExchange ,另外 CustomExchange 的類型必須是 x-delayed-message 。
實(shí)現(xiàn)消息發(fā)送
package com.mq.rabbitmq; import org.springframework.amqp.AmqpException; import org.springframework.amqp.core.Message; import org.springframework.amqp.core.MessagePostProcessor; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.text.SimpleDateFormat; import java.util.Date; @Service public class MessageServiceImpl { @Autowired private RabbitTemplate rabbitTemplate; public void sendMsg(String queueName,String msg) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("消息發(fā)送時(shí)間:"+sdf.format(new Date())); rabbitTemplate.convertAndSend("test_exchange", queueName, msg, new MessagePostProcessor() { @Override public Message postProcessMessage(Message message) throws AmqpException { message.getMessageProperties().setHeader("x-delay",3000); return message; } }); } }
注意在發(fā)送的時(shí)候,必須加上一個(gè)header
x-delay
在這里我設(shè)置的延遲時(shí)間是3秒。
消息消費(fèi)者
package com.mq.rabbitmq; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; @Component public class MessageReceiver { @RabbitListener(queues = "test_queue_1") public void receive(String msg) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("消息接收時(shí)間:"+sdf.format(new Date())); System.out.println("接收到的消息:"+msg); } }
運(yùn)行Spring Boot程序和發(fā)送消息
直接在main方法里運(yùn)行Spring Boot程序,Spring Boot會(huì)自動(dòng)解析 MessageReceiver 類的。
接下來(lái)只需要用Junit運(yùn)行一下發(fā)送消息的接口即可。
package com.mq.rabbitmq; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class RabbitmqApplicationTests { @Autowired private MessageServiceImpl messageService; @Test public void send() { messageService.sendMsg("test_queue_1","hello i am delay msg"); } }
運(yùn)行完后,可以看到如下信息:
消息發(fā)送時(shí)間:2018-05-03 12:44:53
3秒鐘后,Spring Boot控制臺(tái)會(huì)輸出:
消息接收時(shí)間:2018-05-03 12:44:56
接收到的消息:hello i am delay msg
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解析SpringSecurity自定義登錄驗(yàn)證成功與失敗的結(jié)果處理問(wèn)題
這篇文章主要介紹了SpringSecurity系列之自定義登錄驗(yàn)證成功與失敗的結(jié)果處理問(wèn)題,本文通過(guò)實(shí)例給大家講解的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-11-11SpringBoot中TransactionTemplate事務(wù)管理的實(shí)現(xiàn)
Spring Boot提供了多種方式來(lái)管理事務(wù),其中之一是使用TransactionTemplate,本文主要介紹了SpringBoot中TransactionTemplate事務(wù)管理的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2024-04-04在IDEA中如何設(shè)置最多顯示文件標(biāo)簽個(gè)數(shù)
在使用IDEA進(jìn)行編程時(shí),可能會(huì)同時(shí)打開(kāi)多個(gè)文件,當(dāng)文件過(guò)多時(shí),文件標(biāo)簽會(huì)占據(jù)大部分的IDEA界面,影響我們的編程效率,因此,我們可以通過(guò)設(shè)置IDEA的文件標(biāo)簽顯示個(gè)數(shù),來(lái)優(yōu)化我們的編程環(huán)境,具體的設(shè)置方法如下2024-10-10詳解springboot?springsecuroty中的注銷和權(quán)限控制問(wèn)題
這篇文章主要介紹了springboot-springsecuroty?注銷和權(quán)限控制,賬戶注銷需要在SecurityConfig中加入開(kāi)啟注銷功能的代碼,權(quán)限控制要導(dǎo)入springsecurity和thymeleaf的整合依賴,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧2022-03-03SpringBoot下token短信驗(yàn)證登入登出權(quán)限操作(token存放redis,ali短信接口)
這篇文章主要介紹了SpringBoot下token短信驗(yàn)證登入登出權(quán)限操作(token存放redis,ali短信接口),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11Springboot實(shí)現(xiàn)動(dòng)態(tài)定時(shí)任務(wù)流程詳解
通過(guò)重寫(xiě)SchedulingConfigurer方法實(shí)現(xiàn)對(duì)定時(shí)任務(wù)的操作,單次執(zhí)行、停止、啟動(dòng)三個(gè)主要的基本功能,動(dòng)態(tài)的從數(shù)據(jù)庫(kù)中獲取配置的定時(shí)任務(wù)cron信息,通過(guò)反射的方式靈活定位到具體的類與方法中2022-09-09Java實(shí)現(xiàn)簡(jiǎn)單修改文件名的方法分析
這篇文章主要介紹了Java實(shí)現(xiàn)簡(jiǎn)單修改文件名的方法,結(jié)合具體實(shí)例分析了2種比較常用的java文件名修改方法,需要的朋友可以參考下2017-09-09JetBrains?產(chǎn)品輸入激活碼?Key?is?invalid?完美解決方案
JetBrains?系列產(chǎn)品(IDEA、Pycharm?等)使用本站破解教程?(opens?new?window),在輸入激活碼時(shí),部分小伙伴反應(yīng)說(shuō)提示?Key?is?invalid?無(wú)法激活,今天小編給大家分享完美解決方案,感興趣的朋友跟隨小編一起看看吧2022-11-11