Java Redis实现分布式锁

相关解决方案

方案 说明
数据库 基于表的唯一索引
zookeeper 根据zookeeper中的临时有序节点排序
redis 使用setnx命令完成

代码实现

tryLock 方法

ini 复制代码
public String tryLock(String name, int expire) {
    name = name + "_lock";
    String token = UUID.randomUUID().toString();
    RedisConnectionFactory factory = stringRedisTemplate.getConnectionFactory();
    RedisConnection conn = factory.getConnection();
    try {

        //参考redis命令:
        //set key value [EX seconds] [PX milliseconds] [NX|XX]
        Boolean result = conn.set(
                name.getBytes(),
                token.getBytes(),
                Expiration.from(expire, TimeUnit.MILLISECONDS),
                RedisStringCommands.SetOption.SET_IF_ABSENT //NX
        );
        if (result != null && result)
            return token;
    } finally {
        RedisConnectionUtils.releaseConnection(conn, factory,false);
    }
    return null;
}

方法加锁(主要看token这个参数)

typescript 复制代码
/**
 * 未来数据定时刷新
 */
@Scheduled(cron = "0 */1 * * * ?")
public void refresh() {

    String token = cacheService.tryLock("FUTRUE_TASK_SYNC", 1000 * 30);

    if(StringUtils.isNotBlank(token)){
        log.info("未来数据定时刷新---定时任务");

        //获取所有未来数据的集合key
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        for (String futureKey : futureKeys) {
            //future_100_50

            //获取当前数据的key  topic
            String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];

            //按照key和分值查询符合条件的数据
            Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());

            //同步数据
            if (!tasks.isEmpty()) {
                cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                log.info("成功的将" + futureKey + "刷新到了" + topicKey);
            }
        }
    }
}

相关链接:

Springboot集成Redis - 掘金 (juejin.cn)

利用redis解决缓存击穿问题 - 掘金 (juejin.cn)

相关推荐
a程序小傲7 分钟前
京东Java面试被问:Fork/Join框架的使用场景
java·开发语言·后端·postgresql·面试·职场和发展
想用offer打牌11 分钟前
面试官问Redis主从延迟导致脏数据读怎么解决?
redis·后端·面试
appearappear1 小时前
Mac 上重新安装了Cursor 2.2.30,重新配置 springboot 过程记录
java·spring boot·后端
谷哥的小弟1 小时前
Spring Framework源码解析——RequestContext
java·后端·spring·框架·源码
IT_陈寒1 小时前
Vite 5大优化技巧:让你的构建速度飙升50%,开发者都在偷偷用!
前端·人工智能·后端
鹿角片ljp2 小时前
Spring Boot Web入门:从零开始构建web程序
前端·spring boot·后端
程序员阿鹏2 小时前
SpringBoot自动装配原理
java·开发语言·spring boot·后端·spring·tomcat·maven
程序员爱钓鱼2 小时前
Node.js 编程实战:CSV&JSON &Excel 数据处理
前端·后端·node.js
老华带你飞2 小时前
工会管理|基于springboot 工会管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·spring
Echo flower2 小时前
Spring Boot WebFlux 实现流式数据传输与断点续传
java·spring boot·后端