Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to integrate Redisson to realize delay queue in SpringBoot

2025-05-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

Today, I would like to share with you how SpringBoot integrates Redisson to achieve delay queues. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

Working with scen

1. The order was issued successfully and was not paid for 30 minutes. Payment timeout and automatic cancellation of order

2. the order is signed and received, and no evaluation is made 7 days after signing. The order is timed out and not evaluated, and the system is praised by default.

3. The order was issued successfully, the merchant did not receive the order for 5 minutes, and the order was cancelled.

4. Push SMS to remind you when delivery times out.

……

For the scenes with long delay and low real-time performance, we can use the way of task scheduling to poll regularly. Such as: xxl-job

Today we take a relatively simple, lightweight approach, using Redis's delay queue for processing. Of course, there are better solutions, and the best solution can be chosen according to the company's technology selection and business system. For example, delay queues using message middleware Kafka and RabbitMQ

Without discussing its implementation principle, the code directly implements the delay queue based on Redis.

1. Introduce Redisson dependency org.redisson redisson-spring-boot-starter 3.10.52, Nacos configuration Redis connection spring: redis: host: 127.0.0.1 port: 6379 password: 123456 database: 12 timeout: 30003, create RedissonConfig configuration / * * Created by LPB on 2020-04-20. * / @ Configurationpublic 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 delay queue tool * Created by LPB on 2021-04-20. * / @ Slf4j@Componentpublic class RedisDelayQueueUtil {@ Autowired private RedissonClient redissonClient / * add delay queue * @ param value queue value * @ param delay delay time * @ param timeUnit time Unit * @ param * / public void addDelayQueue (T value, long delay, TimeUnit timeUnit, String queueCode) {try {RBlockingDeque blockingDeque = redissonClient.getBlockingDeque (queueCode); RDelayedQueue delayedQueue = redissonClient.getDelayedQueue (blockingDeque) DelayedQueue.offer (value, delay, timeUnit); log.info ("(add delay queue successfully) queue key: {}, queue value: {}, delay time: {}", queueCode, value, timeUnit.toSeconds (delay) + "seconds");} catch (Exception e) {log.error ("(add delay queue failed) {}", e.getMessage ()) Throw new RuntimeException ("(failed to add delay queue)");}} / * * get delay queue * @ param queueCode * @ param * @ return * @ throws InterruptedException * / public T getDelayQueue (String queueCode) throws InterruptedException {RBlockingDeque blockingDeque = redissonClient.getBlockingDeque (queueCode) T value = (T) blockingDeque.take (); return value 5. Create delay queue business enumeration / * * delay queue business enumeration * Created by LPB on 2021-04-20. * / @ Getter@NoArgsConstructor@AllArgsConstructorpublic enum RedisDelayQueueEnum {ORDER_PAYMENT_TIMEOUT ("ORDER_PAYMENT_TIMEOUT", "order payment timeout, automatic order cancellation", "orderPaymentTimeout"), ORDER_TIMEOUT_NOT_EVALUATED ("ORDER_TIMEOUT_NOT_EVALUATED", "order timeout not evaluated") System default praise "," orderTimeoutNotEvaluated ") / * * delay queue Redis Key * / private String code; / * Chinese description * / private String name; / * Bean of specific business implementation of delay queue * can be obtained through the context of Spring * / private String beanId Define delay queue executor / * * delay queue Actuator * Created by LPB on 2021-04-20. * / public interface RedisDelayQueueHandle {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

/ * * order payment timeout class * Created by LPB on 2021-04-20. * / @ Component@Slf4jpublic class OrderPaymentTimeout implements RedisDelayQueueHandle {@ Override public void execute (Map map) {log.info ("(receipt of order payment timeout message) {}", map); / / TODO order payment timeout, automatically cancel order processing business.}

OrderTimeoutNotEvaluated: order timeout does not evaluate delayed queue processing class

/ * * order timeout unevaluated processing class * Created by LPB on 2021-04-20. * / @ Component@Slf4jpublic class OrderTimeoutNotEvaluated implements RedisDelayQueueHandle {@ Override public void execute (Map map) {log.info ("(order timeout delay message) {}", map) / / TODO order timeout is not evaluated. The system defaults to processing business.} 8. Create delay queue consumption thread. Start / * start delay queue * Created by LPB on 2021-04-20. * / @ Slf4j@Componentpublic 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 delay queue abnormal interrupt) {}", e.getMessage ()) }}) .start (); log.info ("(Redis delay queue started successfully)");}}

In the above steps, the core code of Redis delay queue has been completed. Let's write a test interface and simulate it with PostMan.

9. Create a test interface to simulate adding delay queue / * * delay queue Test * Created by LPB on 2020-04-20. * / @ RestControllerpublic class RedisDelayQueueController {@ Autowired private RedisDelayQueueUtil redisDelayQueueUtil; @ PostMapping ("/ addQueue") public void addQueue () {Map map1 = new HashMap (); map1.put ("orderId", "100") Map1.put ("remark", "order payment timeout, automatic cancellation of order"); Map map2 = new HashMap (); map2.put ("orderId", "200"); map2.put ("remark", "order timeout is not evaluated, system default praise") / / add order payment timeout and automatically cancel order delay queue. In order to test the effect, delay 10 seconds redisDelayQueueUtil.addDelayQueue (map1, 10, TimeUnit.SECONDS, RedisDelayQueueEnum.ORDER_PAYMENT_TIMEOUT.getCode ()); / / the order timeout is not evaluated, and the system is praised by default. To test the effect, delay 20 seconds for redisDelayQueueUtil.addDelayQueue (map2, 20, TimeUnit.SECONDS, RedisDelayQueueEnum.ORDER_TIMEOUT_NOT_EVALUATED.getCode ());}} 10. Start SpringBoot project and add delay queue with PostMan calling API

Through the Redis client, you can see that two delay queues have been added successfully

Viewing the IDEA console log shows that the delay queue has been consumed successfully

These are all the contents of the article "how SpringBoot integrates Redisson to implement delay queues". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report