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)

相关推荐
爱吃烤鸡翅的酸菜鱼34 分钟前
Spring Boot 实现 WebSocket 实时通信:从原理到生产级实战
java·开发语言·spring boot·后端·websocket·spring
uzong7 小时前
Mermaid: AI 时代画图的魔法工具
后端·架构
q***69778 小时前
Spring Boot与MyBatis
spring boot·后端·mybatis
IUGEI9 小时前
synchronized的工作机制是怎样的?深入解析synchronized底层原理
java·开发语言·后端·c#
间彧9 小时前
GraalVM Native Image:跨平台能力与编译模式深度解析
后端
间彧9 小时前
GraalVM Native Image 与传统 JVM 内存管理:云原生时代的技术选型指南
后端
r***12389 小时前
SpringBoot最佳实践之 - 使用AOP记录操作日志
java·spring boot·后端
b***748810 小时前
前端GraphQL案例
前端·后端·graphql
LSL666_10 小时前
SpringBoot自动配置类
java·spring boot·后端·自动配置类
q***783710 小时前
Spring Boot 3.X:Unable to connect to Redis错误记录
spring boot·redis·后端