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,加锁失败

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

  • 相关阅读:
    hadoop之 hadoop日志存放路径
    grpc的数据包监控
    HTTP2 概述
    gRPC的简单Go例子
    win下环境变量的设置
    Go的pprof使用
    graphviz
    学习Golang的步骤建议
    golang 的 sync.WaitGroup
    【转】golang的channel的几种用法
  • 原文地址:https://www.cnblogs.com/lidedong/p/15797600.html
Copyright © 2011-2022 走看看