SpringBoot怎么集成Redisson实现延迟队列

SpringBoot怎么集成Redisson实现延迟队列

今天小编给大家分享一下SpringBoot怎么集成Redisson实现延迟队列的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

使用场景

1、下单成功,30分钟未支付。支付超时,自动取消订单

2、订单签收,签收后7天未进行评价。订单超时未评价,系统默认好评

3、下单成功,商家5分钟未接单,订单取消

4、配送超时,推送短信提醒

……

对于延时比较长的场景、实时性不高的场景,我们可以采用任务调度的方式定时轮询处理。如:xxl-job

今天我们采用一种比较简单、轻量级的方式,使用 Redis 的延迟队列来进行处理。当然有更好的解决方案,可根据公司的技术选型和业务体系选择最优方案。如:使用消息中间件Kafka、RabbitMQ的延迟队列

先不讨论其实现原理,直接实战上代码先实现基于 Redis 的延迟队列

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.1port:6379password:123456database:12timeout:3000

3、创建 RedissonConfig 配置

/***CreatedbyLPBon2020/04/20.*/@ConfigurationpublicclassRedissonConfig{@Value("${spring.redis.host}")privateStringhost;@Value("${spring.redis.port}")privateintport;@Value("${spring.redis.database}")privateintdatabase;@Value("${spring.redis.password}")privateStringpassword;@BeanpublicRedissonClientredissonClient(){Configconfig=newConfig();config.useSingleServer().setAddress("redis://"+host+":"+port).setDatabase(database).setPassword(password);returnRedisson.create(config);}}

4、封装 Redis 延迟队列工具类

/***redis延迟队列工具*CreatedbyLPBon2021/04/20.*/@Slf4j@ComponentpublicclassRedisDelayQueueUtil{@AutowiredprivateRedissonClientredissonClient;/***添加延迟队列*@paramvalue队列值*@paramdelay延迟时间*@paramtimeUnit时间单位*@paramqueueCode队列键*@param<T>*/public<T>voidaddDelayQueue(Tvalue,longdelay,TimeUnittimeUnit,StringqueueCode){try{RBlockingDeque<Object>blockingDeque=redissonClient.getBlockingDeque(queueCode);RDelayedQueue<Object>delayedQueue=redissonClient.getDelayedQueue(blockingDeque);delayedQueue.offer(value,delay,timeUnit);log.info("(添加延时队列成功)队列键&#xff1a;{}&#xff0c;队列值&#xff1a;{}&#xff0c;延迟时间&#xff1a;{}",queueCode,value,timeUnit.toSeconds(delay)+"秒");}catch(Exceptione){log.error("(添加延时队列失败){}",e.getMessage());thrownewRuntimeException("(添加延时队列失败)");}}/***获取延迟队列*@paramqueueCode*@param<T>*@return*@throwsInterruptedException*/public<T>TgetDelayQueue(StringqueueCode)throwsInterruptedException{RBlockingDeque<Map>blockingDeque=redissonClient.getBlockingDeque(queueCode);Tvalue=(T)blockingDeque.take();returnvalue;}}

5、创建延迟队列业务枚举

/***延迟队列业务枚举*CreatedbyLPBon2021/04/20.*/@Getter@NoArgsConstructor@AllArgsConstructorpublicenumRedisDelayQueueEnum{ORDER_PAYMENT_TIMEOUT("ORDER_PAYMENT_TIMEOUT","订单支付超时&#xff0c;自动取消订单","orderPaymentTimeout"),ORDER_TIMEOUT_NOT_EVALUATED("ORDER_TIMEOUT_NOT_EVALUATED","订单超时未评价&#xff0c;系统默认好评","orderTimeoutNotEvaluated");/***延迟队列RedisKey*/privateStringcode;/***中文描述*/privateStringname;/***延迟队列具体业务实现的Bean*可通过Spring的上下文获取*/privateStringbeanId;}

6、定义延迟队列执行器

/***延迟队列执行器*CreatedbyLPBon2021/04/20.*/publicinterfaceRedisDelayQueueHandle<T>{voidexecute(Tt);}

7、创建枚举中定义的Bean&#xff0c;并实现延迟队列执行器

  • OrderPaymentTimeout&#xff1a;订单支付超时延迟队列处理类

/***订单支付超时处理类*CreatedbyLPBon2021/04/20.*/@Component@Slf4jpublicclassOrderPaymentTimeoutimplementsRedisDelayQueueHandle<Map>{@Overridepublicvoidexecute(Mapmap){log.info("(收到订单支付超时延迟消息){}",map);//TODO订单支付超时&#xff0c;自动取消订单处理业务...}}

  • OrderTimeoutNotEvaluated&#xff1a;订单超时未评价延迟队列处理类

/***订单超时未评价处理类*CreatedbyLPBon2021/04/20.*/@Component@Slf4jpublicclassOrderTimeoutNotEvaluatedimplementsRedisDelayQueueHandle<Map>{@Overridepublicvoidexecute(Mapmap){log.info("(收到订单超时未评价延迟消息){}",map);//TODO订单超时未评价&#xff0c;系统默认好评处理业务...}}

8、创建延迟队列消费线程&#xff0c;项目启动完成后开启

/***启动延迟队列*CreatedbyLPBon2021/04/20.*/@Slf4j@ComponentpublicclassRedisDelayQueueRunnerimplementsCommandLineRunner{@AutowiredprivateRedisDelayQueueUtilredisDelayQueueUtil;@Overridepublicvoidrun(String...args){newThread(()->{while(true){try{RedisDelayQueueEnum[]queueEnums=RedisDelayQueueEnum.values();for(RedisDelayQueueEnumqueueEnum:queueEnums){Objectvalue=redisDelayQueueUtil.getDelayQueue(queueEnum.getCode());if(value!=null){RedisDelayQueueHandleredisDelayQueueHandle=SpringUtil.getBean(queueEnum.getBeanId());redisDelayQueueHandle.execute(value);}}}catch(InterruptedExceptione){log.error("(Redis延迟队列异常中断){}",e.getMessage());}}}).start();log.info("(Redis延迟队列启动成功)");}}

以上步骤&#xff0c;Redis 延迟队列核心代码已经完成&#xff0c;下面我们写一个测试接口&#xff0c;用 PostMan 模拟测试一下

9、创建一个测试接口&#xff0c;模拟添加延迟队列

/***延迟队列测试*CreatedbyLPBon2020/04/20.*/@RestControllerpublicclassRedisDelayQueueController{@AutowiredprivateRedisDelayQueueUtilredisDelayQueueUtil;@PostMapping("/addQueue")publicvoidaddQueue(){Map<String,String>map1=newHashMap<>();map1.put("orderId","100");map1.put("remark","订单支付超时&#xff0c;自动取消订单");Map<String,String>map2=newHashMap<>();map2.put("orderId","200");map2.put("remark","订单超时未评价&#xff0c;系统默认好评");//添加订单支付超时&#xff0c;自动取消订单延迟队列。为了测试效果&#xff0c;延迟10秒钟redisDelayQueueUtil.addDelayQueue(map1,10,TimeUnit.SECONDS,RedisDelayQueueEnum.ORDER_PAYMENT_TIMEOUT.getCode());//订单超时未评价&#xff0c;系统默认好评。为了测试效果&#xff0c;延迟20秒钟redisDelayQueueUtil.addDelayQueue(map2,20,TimeUnit.SECONDS,RedisDelayQueueEnum.ORDER_TIMEOUT_NOT_EVALUATED.getCode());}}

10、启动 SpringBoot 项目&#xff0c;用 PostMan 调用接口添加延迟队列

  • 通过 Redis 客户端可看到两个延迟队列已添加成功

  • 查看 IDEA 控制台日志可看到延迟队列已消费成功

以上就是“SpringBoot怎么集成Redisson实现延迟队列”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注恰卡编程网行业资讯频道。

发布于 2022-04-11 21:11:29
收藏
分享
海报
0 条评论
29
上一篇:跨省异地就医怎么办理(异地医保怎么办理) 下一篇:怎么提升BERT的推断速度
目录

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码