zoukankan      html  css  js  c++  java
  • redis分布式锁,加锁代码逻辑

    public boolean lock(String key, String value) {
        if(redisTemplate.opsForValue().setIfAbsent(key, value)) {
            return true;
        }
        String currentValue = redisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(currentValue)
            && Long.parseLong(currentValue) < System.currentTimeMillis()) {
    
            String oldValue = redisTemplate.opsForValue().getAndSet(key, value);
            if (!StringUtils.isEmpty(oldValue) && oldValue.equals(currentValue)) {
                return true;
            }
        }
        return false;
    }

    假如现在两个线程A和B同时执行lock()方法,也就是这两个线程的value是完全相同的,都为value=2020-12-19,而他们都执行 String oldValue = redisTemplate.opsForValue().getAndSet(key, value);,会有一个先执行一个后执行:

    假如线程A先执行,返回的oldValue=2020-12-18,同时设置value = 2020-12-19,由于oldvalue=currentValue返回true,即A线程加了锁;

    此时B线程继续执行 ,返回的oldValue=2020-12-19,oldvalue!=currentValue,返回false,加锁失败

    所以这段代码的逻辑是只会让一个线程加锁

  • 相关阅读:
    函数
    registry搭建及镜像管理-harbor
    用户输入和while 循环
    dockerfile
    字典,set
    if 语句
    alpine操作
    循环:列表,元组
    列表
    docker跨主机通信-overlay
  • 原文地址:https://www.cnblogs.com/lidedong/p/15797600.html
Copyright © 2011-2022 走看看