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)

相关推荐
why1512 小时前
深信服golang面经
开发语言·后端·golang
言之。2 小时前
Go语言中new与make的深度解析
开发语言·后端·golang
田秋浩3 小时前
Springboot 跨域拦截器配置说明
java·spring boot·后端
汇匠源4 小时前
Spring Boot + +小程序, 快速开发零工市场小程序
spring boot·后端·小程序
码农爱java5 小时前
Elasticsearch 深入分析三种分页查询【Elasticsearch 深度分页】
java·大数据·spring boot·后端·elasticsearch·全文检索
黄暄5 小时前
Spring Boot 登录实现:JWT 与 Session 全面对比与实战讲解
javascript·网络·spring boot·后端
设计师小聂!6 小时前
Spring ---IOC容器和DI的具体应用
java·后端·spring
我命由我123456 小时前
IDEA - Windows IDEA 代码块展开与折叠(基础折叠操作、高级折叠操作)
java·笔记·后端·java-ee·intellij-idea·学习方法·intellij idea
A_bad_horse6 小时前
Spring Boot-Swagger离线文档(插件方式)
java·spring boot·后端
Brookty7 小时前
【MySQL】数据库约束
数据库·后端·学习·mysql