(三)延时任务篇——通过redis的zset数据结构,实现延迟任务实战

前言

在前一篇内容中我们介绍了如何使用redis key过期失效的监控,完成任务延时关闭的功能,同时官方并不支持使用此种方式实现,由于其安全性较低,存在数据丢失的情况。本节内容是对延迟任务的又一实现方案,通过redis zset的数据结构完成延迟任务。使用一个常量order作为key,订单id作为value值,任务的过期时间作为score值,通过定时任务取前100名的数据,比较score值和当前时间的大小,如果该值小于当前时间,则证明该订单已过期,完成关单的操作,并将该订单数据在redis中删除。

正文

  • 项目集成redis,可参考上一节内容
  • 引入redis的pom依赖

    <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis-reactive</artifactId> </dependency>
  • 在application.yml中添加redis的配置信息

    spring:
    data:
    redis:
    host: 127.0.0.1
    port: 6379
    database: 0
    connect-timeout: 30000
    timeout: 30000
    lettuce:
    pool:
    enabled: true
    max-active: 200
    max-idle: 50
    max-wait: -1
    min-idle: 10
    shutdown-timeout: 100

  • 创建订单测试接口
java 复制代码
    @Operation(summary = "创建订单-redis-zset")
    @PostMapping("saveOrderByRedisZet")
    public ApiResponse saveOrderByRedisZet() {
        String orderId = String.valueOf(IdWorker.getId());
        stringRedisTemplate.opsForZSet().add("order", orderId, System.currentTimeMillis() + 60000);
        return ApiResponse.ok();
    }
  • 开启定时任务,监控订单的状态
java 复制代码
package com.yundi.xyxc.tps.job;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;


@Slf4j
@EnableScheduling
@Component
public class OrderJob {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 注意:如果是分布式架构,这里需要使用分布式任务的方式,例如xxl-job或者使用分布式锁+定时任务
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void createOrder() {
        ZSetOperations<String, String> operations = stringRedisTemplate.opsForZSet();
        //查询过期排名前100的订单
        Set<ZSetOperations.TypedTuple<String>> top100 = operations.rangeWithScores("order", 0, 99);
        assert top100 != null;
        for (ZSetOperations.TypedTuple<String> tuple : top100) {
            log.info("Member: {}, Score: {}", tuple.getValue(), tuple.getScore());
            //订单小于当前时间,订单过期,删除该订单
            if (tuple.getScore() < System.currentTimeMillis()) {
                log.info("订单过期,删除订单:{}", tuple.getValue());
                operations.remove("order", tuple.getValue());
            }
        }
        log.info("--------------------------------------------------------------");

    }

}

**PS:**此处需要注意的是,如果是分布式系统,此处需要使用分布锁+@Scheduled定时任务,保证数据的安全性,以免产生并发问题。同时需要保证定时任务的执行时间合理根据任务的实际完成时间。

  • 启动项目,通过接口调用订单创建接口
  • 查看关单输出,过期的订单被关单并删除

结语

使用redis的zset数据结构完成延迟任务,相较于监控key失效更加安全,不会出现数据的丢失,同时相较于某些mq消息中间件的延迟对列,更加灵活,可以设置任意时间的延迟过期任务。关于使用redis的zset数据结构,实现延迟任务的内容到这里就结束了。。。

相关推荐
陆少枫1 小时前
MySQL基础关键_005_DQL(四)
数据库·mysql
佩奇的技术笔记1 小时前
Java学习手册:关系型数据库基础
java·数据库·学习
大G哥2 小时前
Nginx代理、缓存与Rewrite
运维·nginx·缓存
Yan-英杰2 小时前
npm error code CERT_HAS_EXPIRED
服务器·前端·数据库·人工智能·mysql·npm·node.js
MindibniM3 小时前
二种MVCC对比分析
数据库·框架·mvcc
涤生大数据3 小时前
海量数据存储与分析:HBase vs ClickHouse vs Doris 三大数据库优劣对比指南
数据库·clickhouse·hbase
shenyan~3 小时前
关于Python:7. Python数据库操作
数据库
长流小哥3 小时前
MySQL数据操作全攻略:DML增删改与DQL高级查询实战指南
数据库·mysql
麓殇⊙3 小时前
MySQL--索引入门
android·数据库·mysql
苦学编程啊3 小时前
深入理解Redis SDS:高性能字符串的终极设计指南
数据库·redis·缓存·c#