How SpringBoot integrates Redisson to implement delay queue
May 30, 2023 pm 02:40 PMUsage Scenarios
1. The order was successfully placed but not paid for 30 minutes. Payment timeout,Automatic cancellation of order
2. Order receipt,No evaluation will be conducted within 7 days after receipt. The order timed out and was not evaluated,The system defaults to a positive review
3. The order was placed successfully,The merchant did not receive the order within 5 minutes,The order was cancelled
4.The delivery timed out xff0c;Push SMS reminder
……
For scenarios with long delays and low real-time performance, we can use task scheduling to process polling at regular intervals. For example,:xxl-job
Today we adopt a relatively simple and lightweight method-using Redis' delay queue for processing. Of course there are better solutions - you can choose the optimal solution based on the company's technology selection and business system. For example, use the message middleware Kafka and RabbitMQ's delay queue
Let's not discuss its implementation principle. Let's go directly to the actual code and first implement the Redis-based delay queue
1. Introduce Redisson dependency
<dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-boot-starter</artifactId> <version>3.10.5</version> </dependency>
2. Nacos configuration Redis connection
spring: redis: host: 127.0.0.1 port: 6379 password: 123456 database: 12 timeout: 3000
3. Create RedissonConfig configuration
/** * 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. Encapsulate Redis delay queue tool class
/** * redis延遲隊列工具 * Created by LPB on 2021/04/20. */ @Slf4j @Component public class RedisDelayQueueUtil { @Autowired private RedissonClient redissonClient; /** * 添加延遲隊列 * @param value 隊列值 * @param delay 延遲時間 * @param timeUnit 時間單位 * @param queueCode 隊列鍵 * @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("(添加延時隊列成功) 隊列鍵:{},隊列值:{},延遲時間:{}", queueCode, value, timeUnit.toSeconds(delay) + "秒"); } catch (Exception e) { log.error("(添加延時隊列失敗) {}", e.getMessage()); throw new RuntimeException("(添加延時隊列失敗)"); } } /** * 獲取延遲隊列 * @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. Create a delay queue business enumeration
/** * 延遲隊列業(yè)務(wù)枚舉 * Created by LPB on 2021/04/20. */ @Getter @NoArgsConstructor @AllArgsConstructor public enum RedisDelayQueueEnum { ORDER_PAYMENT_TIMEOUT("ORDER_PAYMENT_TIMEOUT","訂單支付超時,自動取消訂單", "orderPaymentTimeout"), ORDER_TIMEOUT_NOT_EVALUATED("ORDER_TIMEOUT_NOT_EVALUATED", "訂單超時未評價,系統(tǒng)默認好評", "orderTimeoutNotEvaluated"); /** * 延遲隊列 Redis Key */ private String code; /** * 中文描述 */ private String name; /** * 延遲隊列具體業(yè)務(wù)實現(xiàn)的 Bean * 可通過 Spring 的上下文獲取 */ private String beanId; }
6. Define the delay queue executor
/** * 延遲隊列執(zhí)行器 * Created by LPB on 2021/04/20. */ public interface RedisDelayQueueHandle<T> { void execute(T t); }
7. Create the Bean, defined in the enumeration and implement the delay queue executor
OrderPaymentTimeout:Order payment timeout delay queue processing class
/** * 訂單支付超時處理類 * Created by LPB on 2021/04/20. */ @Component @Slf4j public class OrderPaymentTimeout implements RedisDelayQueueHandle<Map> { @Override public void execute(Map map) { log.info("(收到訂單支付超時延遲消息) {}", map); // TODO 訂單支付超時,自動取消訂單處理業(yè)務(wù)... } }
DelayQueueProcessorForUnevaluatedOrders: Delay queue processing class for processing unevaluated orders , used when the order times out and is not evaluated
/** * 訂單超時未評價處理類 * Created by LPB on 2021/04/20. */ @Component @Slf4j public class OrderTimeoutNotEvaluated implements RedisDelayQueueHandle<Map> { @Override public void execute(Map map) { log.info("(收到訂單超時未評價延遲消息) {}", map); // TODO 訂單超時未評價,系統(tǒng)默認好評處理業(yè)務(wù)... } }
8. Create a delay queue consumption thread,Start after the project is started
/** * 啟動延遲隊列 * 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延遲隊列異常中斷) {}", e.getMessage()); } } }).start(); log.info("(Redis延遲隊列啟動成功)"); } }
The above steps ,Redis delay queue core code has been completed,Let’s write a test interface,Use PostMan to simulate and test it
9. Create a test interface,Simulation Add a delay queue
/** * 延遲隊列測試 * 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", "訂單支付超時,自動取消訂單"); Map<String, String> map2 = new HashMap<>(); map2.put("orderId", "200"); map2.put("remark", "訂單超時未評價,系統(tǒng)默認好評"); // 添加訂單支付超時,自動取消訂單延遲隊列。為了測試效果,延遲10秒鐘 redisDelayQueueUtil.addDelayQueue(map1, 10, TimeUnit.SECONDS, RedisDelayQueueEnum.ORDER_PAYMENT_TIMEOUT.getCode()); // 訂單超時未評價,系統(tǒng)默認好評。為了測試效果,延遲20秒鐘 redisDelayQueueUtil.addDelayQueue(map2, 20, TimeUnit.SECONDS, RedisDelayQueueEnum.ORDER_TIMEOUT_NOT_EVALUATED.getCode()); } }
10. Start the SpringBoot project,Use the PostMan calling interface to add a delay queue
You can see through the Redis client that the two delay queues have been Added successfully
Check the IDEA console log to see that the delay queue has been consumed successfully
The above is the detailed content of How SpringBoot integrates Redisson to implement delay queue. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

If you have been using Redis before, you will get twice the result with half the effort by using Redisson. Redisson provides the simplest and most convenient way to use Redis. The purpose of Redisson is to promote users' separation of concerns (Separation of Concern) from Redis, so that users can focus more on processing business logic.
