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)

相关推荐
不光头强4 小时前
spring cloud知识总结
后端·spring·spring cloud
GetcharZp7 小时前
告别 Python 依赖!用 LangChainGo 打造高性能大模型应用,Go 程序员必看!
后端
阿里加多7 小时前
第 4 章:Go 线程模型——GMP 深度解析
java·开发语言·后端·golang
小小李程序员7 小时前
Langchain4j工具调用获取不到ThreadLocal
java·后端·ai
GreenTea10 小时前
AI Agent 评测的下半场:从方法论到落地实践
前端·人工智能·后端
我是若尘10 小时前
Harness Engineering:2026 年 AI 编程的核心战场
前端·后端·程序员
IT_陈寒12 小时前
折腾一天才明白:Vite的热更新为什么偶尔会罢工
前端·人工智能·后端
希望永不加班12 小时前
SpringBoot 自动配置类加载顺序与优先级
java·spring boot·后端·spring·mybatis