使用場(chǎng)景
1、下單成功,30分鐘未支付。支付超時(shí),自動(dòng)取消訂單
2、訂單簽收,簽收后7天未進(jìn)行評(píng)價(jià)。訂單超時(shí)未評(píng)價(jià),系統(tǒng)默認(rèn)好評(píng)
3、下單成功,商家5分鐘未接單,訂單取消
4、配送超時(shí),推送短信提醒
……
對(duì)于延時(shí)比較長(zhǎng)的場(chǎng)景、實(shí)時(shí)性不高的場(chǎng)景,我們可以采用任務(wù)調(diào)度的方式定時(shí)輪詢處理。如:xxl-job
今天我們采用一種比較簡(jiǎn)單、輕量級(jí)的方式,使用 Redis 的延遲隊(duì)列來(lái)進(jìn)行處理。當(dāng)然有更好的解決方案,可根據(jù)公司的技術(shù)選型和業(yè)務(wù)體系選擇最優(yōu)方案。如:使用消息中間件Kafka、RabbitMQ?的延遲隊(duì)列
先不討論其實(shí)現(xiàn)原理,直接實(shí)戰(zhàn)上代碼先實(shí)現(xiàn)基于 Redis 的延遲隊(duì)列
1、引入 Redisson 依賴
<dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-boot-starter</artifactId> <version>3.10.5</version> </dependency>
2、Nacos 配置 Redis 連接
spring: redis: host: 127.0.0.1 port: 6379 password: 123456 database: 12 timeout: 3000
3、創(chuàng)建 RedissonConfig 配置
/** * Created by LPB on 2020/04/20. */ @Configuration public class RedissonConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Value("${spring.redis.database}") private int database; @Value("${spring.redis.password}") private String password; @Bean public RedissonClient redissonClient() { Config config = new Config(); config.useSingleServer() .setAddress("redis://" + host + ":" + port) .setDatabase(database) .setPassword(password); return Redisson.create(config); } }
4、封裝 Redis 延遲隊(duì)列工具類(lèi)
/** * redis延遲隊(duì)列工具 * Created by LPB on 2021/04/20. */ @Slf4j @Component public class RedisDelayQueueUtil { @Autowired private RedissonClient redissonClient; /** * 添加延遲隊(duì)列 * @param value 隊(duì)列值 * @param delay 延遲時(shí)間 * @param timeUnit 時(shí)間單位 * @param queueCode 隊(duì)列鍵 * @param <T> */ public <T> void addDelayQueue(T value, long delay, TimeUnit timeUnit, String queueCode){ try { RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque(queueCode); RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque); delayedQueue.offer(value, delay, timeUnit); log.info("(添加延時(shí)隊(duì)列成功) 隊(duì)列鍵:{},隊(duì)列值:{},延遲時(shí)間:{}", queueCode, value, timeUnit.toSeconds(delay) + "秒"); } catch (Exception e) { log.error("(添加延時(shí)隊(duì)列失敗) {}", e.getMessage()); throw new RuntimeException("(添加延時(shí)隊(duì)列失敗)"); } } /** * 獲取延遲隊(duì)列 * @param queueCode * @param <T> * @return * @throws InterruptedException */ public <T> T getDelayQueue(String queueCode) throws InterruptedException { RBlockingDeque<Map> blockingDeque = redissonClient.getBlockingDeque(queueCode); T value = (T) blockingDeque.take(); return value; } }
5、創(chuàng)建延遲隊(duì)列業(yè)務(wù)枚舉
/** * 延遲隊(duì)列業(yè)務(wù)枚舉 * Created by LPB on 2021/04/20. */ @Getter @NoArgsConstructor @AllArgsConstructor public enum RedisDelayQueueEnum { ORDER_PAYMENT_TIMEOUT("ORDER_PAYMENT_TIMEOUT","訂單支付超時(shí),自動(dòng)取消訂單", "orderPaymentTimeout"), ORDER_TIMEOUT_NOT_EVALUATED("ORDER_TIMEOUT_NOT_EVALUATED", "訂單超時(shí)未評(píng)價(jià),系統(tǒng)默認(rèn)好評(píng)", "orderTimeoutNotEvaluated"); /** * 延遲隊(duì)列 Redis Key */ private String code; /** * 中文描述 */ private String name; /** * 延遲隊(duì)列具體業(yè)務(wù)實(shí)現(xiàn)的 Bean * 可通過(guò) Spring 的上下文獲取 */ private String beanId; }
6、定義延遲隊(duì)列執(zhí)行器
/** * 延遲隊(duì)列執(zhí)行器 * Created by LPB on 2021/04/20. */ public interface RedisDelayQueueHandle<T> { void execute(T t); }
7、創(chuàng)建枚舉中定義的Bean,并實(shí)現(xiàn)延遲隊(duì)列執(zhí)行器
OrderPaymentTimeout:訂單支付超時(shí)延遲隊(duì)列處理類(lèi)
/** * 訂單支付超時(shí)處理類(lèi) * Created by LPB on 2021/04/20. */ @Component @Slf4j public class OrderPaymentTimeout implements RedisDelayQueueHandle<Map> { @Override public void execute(Map map) { log.info("(收到訂單支付超時(shí)延遲消息) {}", map); // TODO 訂單支付超時(shí),自動(dòng)取消訂單處理業(yè)務(wù)... } }
DelayQueueProcessorForUnevaluatedOrders: 處理未評(píng)價(jià)訂單的延遲隊(duì)列處理類(lèi),用于訂單超時(shí)未評(píng)價(jià)的情況
/** * 訂單超時(shí)未評(píng)價(jià)處理類(lèi) * Created by LPB on 2021/04/20. */ @Component @Slf4j public class OrderTimeoutNotEvaluated implements RedisDelayQueueHandle<Map> { @Override public void execute(Map map) { log.info("(收到訂單超時(shí)未評(píng)價(jià)延遲消息) {}", map); // TODO 訂單超時(shí)未評(píng)價(jià),系統(tǒng)默認(rèn)好評(píng)處理業(yè)務(wù)... } }
8、創(chuàng)建延遲隊(duì)列消費(fèi)線程,項(xiàng)目啟動(dòng)完成后開(kāi)啟
/** * 啟動(dòng)延遲隊(duì)列 * Created by LPB on 2021/04/20. */ @Slf4j @Component public class RedisDelayQueueRunner implements CommandLineRunner { @Autowired private RedisDelayQueueUtil redisDelayQueueUtil; @Override public void run(String... args) { new Thread(() -> { while (true){ try { RedisDelayQueueEnum[] queueEnums = RedisDelayQueueEnum.values(); for (RedisDelayQueueEnum queueEnum : queueEnums) { Object value = redisDelayQueueUtil.getDelayQueue(queueEnum.getCode()); if (value != null) { RedisDelayQueueHandle redisDelayQueueHandle = SpringUtil.getBean(queueEnum.getBeanId()); redisDelayQueueHandle.execute(value); } } } catch (InterruptedException e) { log.error("(Redis延遲隊(duì)列異常中斷) {}", e.getMessage()); } } }).start(); log.info("(Redis延遲隊(duì)列啟動(dòng)成功)"); } }
以上步驟,Redis 延遲隊(duì)列核心代碼已經(jīng)完成,下面我們寫(xiě)一個(gè)測(cè)試接口,用 PostMan 模擬測(cè)試一下
9、創(chuàng)建一個(gè)測(cè)試接口,模擬添加延遲隊(duì)列
/** * 延遲隊(duì)列測(cè)試 * Created by LPB on 2020/04/20. */ @RestController public class RedisDelayQueueController { @Autowired private RedisDelayQueueUtil redisDelayQueueUtil; @PostMapping("/addQueue") public void addQueue() { Map<String, String> map1 = new HashMap<>(); map1.put("orderId", "100"); map1.put("remark", "訂單支付超時(shí),自動(dòng)取消訂單"); Map<String, String> map2 = new HashMap<>(); map2.put("orderId", "200"); map2.put("remark", "訂單超時(shí)未評(píng)價(jià),系統(tǒng)默認(rèn)好評(píng)"); // 添加訂單支付超時(shí),自動(dòng)取消訂單延遲隊(duì)列。為了測(cè)試效果,延遲10秒鐘 redisDelayQueueUtil.addDelayQueue(map1, 10, TimeUnit.SECONDS, RedisDelayQueueEnum.ORDER_PAYMENT_TIMEOUT.getCode()); // 訂單超時(shí)未評(píng)價(jià),系統(tǒng)默認(rèn)好評(píng)。為了測(cè)試效果,延遲20秒鐘 redisDelayQueueUtil.addDelayQueue(map2, 20, TimeUnit.SECONDS, RedisDelayQueueEnum.ORDER_TIMEOUT_NOT_EVALUATED.getCode()); } }
10、啟動(dòng) SpringBoot 項(xiàng)目,用 PostMan 調(diào)用接口添加延遲隊(duì)列
通過(guò) Redis 客戶端可看到兩個(gè)延遲隊(duì)列已添加成功
查看 IDEA 控制臺(tái)日志可看到延遲隊(duì)列已消費(fèi)成功
以上是SpringBoot怎么集成Redisson實(shí)現(xiàn)延遲隊(duì)列的詳細(xì)內(nèi)容。更多信息請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費(fèi)脫衣服圖片

Undresser.AI Undress
人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover
用于從照片中去除衣服的在線人工智能工具。

Clothoff.io
AI脫衣機(jī)

Video Face Swap
使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱門(mén)文章

熱工具

記事本++7.3.1
好用且免費(fèi)的代碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
功能強(qiáng)大的PHP集成開(kāi)發(fā)環(huán)境

Dreamweaver CS6
視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版
神級(jí)代碼編輯軟件(SublimeText3)

熱門(mén)話題

Jasypt介紹Jasypt是一個(gè)java庫(kù),它允許開(kāi)發(fā)員以最少的努力為他/她的項(xiàng)目添加基本的加密功能,并且不需要對(duì)加密工作原理有深入的了解用于單向和雙向加密的高安全性、基于標(biāo)準(zhǔn)的加密技術(shù)。加密密碼,文本,數(shù)字,二進(jìn)制文件...適合集成到基于Spring的應(yīng)用程序中,開(kāi)放API,用于任何JCE提供程序...添加如下依賴:com.github.ulisesbocchiojasypt-spring-boot-starter2.1.1Jasypt好處保護(hù)我們的系統(tǒng)安全,即使代碼泄露,也可以保證數(shù)據(jù)源的

一、Redis實(shí)現(xiàn)分布式鎖原理為什么需要分布式鎖在聊分布式鎖之前,有必要先解釋一下,為什么需要分布式鎖。與分布式鎖相對(duì)就的是單機(jī)鎖,我們?cè)趯?xiě)多線程程序時(shí),避免同時(shí)操作一個(gè)共享變量產(chǎn)生數(shù)據(jù)問(wèn)題,通常會(huì)使用一把鎖來(lái)互斥以保證共享變量的正確性,其使用范圍是在同一個(gè)進(jìn)程中。如果換做是多個(gè)進(jìn)程,需要同時(shí)操作一個(gè)共享資源,如何互斥呢?現(xiàn)在的業(yè)務(wù)應(yīng)用通常是微服務(wù)架構(gòu),這也意味著一個(gè)應(yīng)用會(huì)部署多個(gè)進(jìn)程,多個(gè)進(jìn)程如果需要修改MySQL中的同一行記錄,為了避免操作亂序?qū)е屡K數(shù)據(jù),此時(shí)就需要引入分布式鎖了。想要實(shí)現(xiàn)分

1、自定義RedisTemplate1.1、RedisAPI默認(rèn)序列化機(jī)制基于API的Redis緩存實(shí)現(xiàn)是使用RedisTemplate模板進(jìn)行數(shù)據(jù)緩存操作的,這里打開(kāi)RedisTemplate類(lèi),查看該類(lèi)的源碼信息publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations,BeanClassLoaderAware{//聲明了key、value的各種序列化方式,初始值為空@NullableprivateRedisSe

springboot讀取文件,打成jar包后訪問(wèn)不到最新開(kāi)發(fā)出現(xiàn)一種情況,springboot打成jar包后讀取不到文件,原因是打包之后,文件的虛擬路徑是無(wú)效的,只能通過(guò)流去讀取。文件在resources下publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

使用場(chǎng)景1、下單成功,30分鐘未支付。支付超時(shí),自動(dòng)取消訂單2、訂單簽收,簽收后7天未進(jìn)行評(píng)價(jià)。訂單超時(shí)未評(píng)價(jià),系統(tǒng)默認(rèn)好評(píng)3、下單成功,商家5分鐘未接單,訂單取消4、配送超時(shí),推送短信提醒……對(duì)于延時(shí)比較長(zhǎng)的場(chǎng)景、實(shí)時(shí)性不高的場(chǎng)景,我們可以采用任務(wù)調(diào)度的方式定時(shí)輪詢處理。如:xxl-job今天我們采

在Springboot+Mybatis-plus不使用SQL語(yǔ)句進(jìn)行多表添加操作我所遇到的問(wèn)題準(zhǔn)備工作在測(cè)試環(huán)境下模擬思維分解一下:創(chuàng)建出一個(gè)帶有參數(shù)的BrandDTO對(duì)象模擬對(duì)后臺(tái)傳遞參數(shù)我所遇到的問(wèn)題我們都知道,在我們使用Mybatis-plus中進(jìn)行多表操作是極其困難的,如果你不使用Mybatis-plus-join這一類(lèi)的工具,你只能去配置對(duì)應(yīng)的Mapper.xml文件,配置又臭又長(zhǎng)的ResultMap,然后再去寫(xiě)對(duì)應(yīng)的sql語(yǔ)句,這種方法雖然看上去很麻煩,但具有很高的靈活性,可以讓我們

SpringBoot和SpringMVC都是Java開(kāi)發(fā)中常用的框架,但它們之間有一些明顯的差異。本文將探究這兩個(gè)框架的特點(diǎn)和用途,并對(duì)它們的差異進(jìn)行比較。首先,我們來(lái)了解一下SpringBoot。SpringBoot是由Pivotal團(tuán)隊(duì)開(kāi)發(fā)的,它旨在簡(jiǎn)化基于Spring框架的應(yīng)用程序的創(chuàng)建和部署。它提供了一種快速、輕量級(jí)的方式來(lái)構(gòu)建獨(dú)立的、可執(zhí)行

如果你之前是在用 Redis 的話,那使用 Redisson 的話將會(huì)事半功倍,Redisson 提供了使用 Redis的最簡(jiǎn)單和最便捷的方法。Redisson的宗旨是促進(jìn)使用者對(duì) Redis 的關(guān)注分離(Separation of Concern),從而讓使用者能夠?qū)⒕Ω械胤旁谔幚順I(yè)務(wù)邏輯上。
