zoukankan      html  css  js  c++  java
  • 分布式锁-基于redis的分布式锁实现

    在微服务中缓存重建的时候一般会考虑使用分布式锁来避免缓存重建工作在不同的服务中重复执行

    以下是使用Spring Cloud工程,基于Redis实现的分布式锁, 使用时需要引入 spring-boot-data-redis 依赖

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Component;
    
    import java.util.concurrent.TimeUnit;
    
    @Component
    public class RedisLockSample {
    
        @Autowired
        private RedisTemplate redisTemplate;
    
        public synchronized String reconstructionCache() {
            boolean findValue = false;
            try{
                for (int i = 0; i < 3; i++) {
                    // 使用nx特性获取锁
                    boolean lock = redisTemplate.boundValueOps("lock").setIfAbsent("test");
                    if (lock) {
                        // 多重检查避免无效更新
                        if (redisTemplate.hasKey("data:cache")) {
                            findValue = true;
                            break;
                        }
    
                        redisTemplate.opsForValue().set("data:cache", "业务数据部分");
                        findValue = true;
                        break;
                    }
                    // 无法获取到锁 进入等待
                    try {
                        TimeUnit.MILLISECONDS.sleep(200L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // 检查值是否被其他服务设置,如果被设置了则提前退出锁获取流程
                    if (redisTemplate.hasKey("data:cache")) { 
                        findValue = true;
                        break;
                    }
                }
                return findValue ? (String) redisTemplate.opsForValue().get("data:cache") : null;
            }finally {
                // 释放锁
                redisTemplate.delete("lock");
            }
        }
    
    }
  • 相关阅读:
    ASP.NET MVC 4使用jQuery传递对象至后台方法
    大沙发斯蒂芬
    2017年年总结
    Java将HTML导出为PDF
    华硕笔记本安装Ubuntu 17.04版本
    全站启用HTTPS配置详解
    设计模式-1 单例模式
    基础知识扫盲--1 抽象类和接口
    ASP.Net 管道模型 VS Asp.Net Core 管道 总结
    索引深入理解
  • 原文地址:https://www.cnblogs.com/banywl/p/15376694.html
Copyright © 2011-2022 走看看