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)

相关推荐
追逐时光者42 分钟前
一个基于 .NET 8 开源免费、高性能、低占用的博客系统
后端·.net
方圆想当图灵1 小时前
深入理解软件设计:领域驱动设计实战
后端·领域驱动设计
网小鱼的学习笔记2 小时前
flask静态资源与模板页面、模板用户登录案例
后端·python·flask
ZHOU_WUYI2 小时前
多组件 flask 项目
后端·flask
十六点五3 小时前
JVM(4)——引用类型
java·开发语言·jvm·后端
周末程序猿3 小时前
Linux高性能网络编程十谈|9个C++的开源的网络框架
后端·算法
笑傲菌4 小时前
【编程二三事】初识Channel
后端
倔强青铜三4 小时前
🚀LlamaIndex中文教程(1)----对接Qwen3大模型
人工智能·后端·python
小码编匠4 小时前
基于 SpringBoot 开源智碳能源管理系统(EMS),赋能企业节能减排与碳管理
java·后端·开源
知其然亦知其所以然4 小时前
Spring AI:ChatClient API 真香警告!我用它把聊天机器人卷上天了!
后端·aigc·ai编程