redisson实现可靠高效的延迟队列

1、对于一些特殊场景需要延迟消息来改变状态等,比如订单半小时后过期,某个活动在各个时间段用户的动作如果没做就接受消息修改状态,这种方式很实用。采用RDelayedQueue

2、具体原理网上有参数,这是一种拉取redis中zset的数据方式。经过测试很稳定
https://zhuanlan.zhihu.com/p/343811173

3、具体代码
3.1、发送消息

        RBlockingDeque<Long> blockingDeque = redissonClient.getBlockingDeque("QUEUE:ORDER");
        RDelayedQueue<Long> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
        long end = LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
                .atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        long now = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        if (end > now)
            delayedQueue.offer(orderId, end - now, TimeUnit.MILLISECONDS);

3.2、接收消息处理

@Component
@Order(1)
public class StartServerConfig implements ApplicationRunner {
    private final static Logger LOGGER = LoggerFactory.getLogger(StartServerConfig.class);
    @Resource
    private RedissonClient redissonClient;

    private final TaskPool executorService = TaskPoolFactory
            .getTaskPool(5, 10, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100),
                    new ThreadPoolExecutor.AbortPolicy());

    @Override
    public void run(ApplicationArguments args) {
        RBlockingDeque<Long> blockingDeque = redissonClient.getBlockingDeque("QUEUE:ORDER");
        while (true) {
            try {
                Long poll = blockingDeque.take();
                if (Objects.nonNull(poll))
                    executorService.submit(new OrderExecutorTask(poll));
            } catch (InterruptedException | BusinessException e) {
                e.printStackTrace();
                //日志平台记录
                LOGGER.error(e.getMessage());
            }
        }
    }
}
public class OrderExecutorTask extends ExecutorTask {
    private final static Logger LOGGER = LoggerFactory.getLogger(OrderExecutorTask.class);
    private Long orderId;
    public OrderExecutorTask(Long orderId){
        this.orderId = orderId;
    }
    @Override
    public void execute() {
        LOGGER.info("=======");
        LOGGER.info("订单ID:{}",orderId);
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sunnyboy_4

你的鼓励是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值