分布式锁-基于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");
        }
    }

}
posted @ 2021-10-07 18:38  半雨微凉  阅读(63)  评论(0编辑  收藏  举报