20 minutes to take you familiar with the Redisson distributed lock design scheme

Article Directory

Preface

If you find it useful, remember to give the blogger a thumbs-up, comment, bookmark one-click three-links , writing is not easy ^ _ ^.
And I heard that people who like it will not have bad luck every day . If it is really useless, then please come often !!!


20 minutes to take you familiar with the Redisson distributed lock design scheme

01 Revisit distributed locks

Distributed lock is also a kind of lock mechanism. It only appeared to deal with the distributed environment.
It is not a brand-new component or middleware. It is just a mechanism, an implementation method, or a solution. .
It is used to ensure that in a distributed environment, multiple clients or multiple service processes mutually exclusive access to "shared resources" through a lock mechanism, so as to avoid problems such as concurrency security and data inconsistency.


01::01 Several requirements for the design of distributed locks

The industry generally has several requirements:

  1. Exclusivity
  2. Avoid deadlock
  3. High availability
  4. Reentrant
  5. Fair lock (optional)

01::02 How to understand distributed locks?

That is, through the third party's atomic behavior to protect the security problems under high concurrency.
Maybe this sentence is a bit convoluted for beginners, it doesn't matter, it will be helpful to write it down.


02 Advantages of Redisson distributed lock design

Redisson distributed locks solve the shortcomings of implementing distributed locks based on redis atomic operations.


02::01 Insufficiency of Redis distributed lock design

  1. When performing Redis atomic operations, you need to set EXPIRE, that is, the TTL of the Reds key. The expiration time of different business scenarios is different. If the setting is improper, it may affect the performance of the system and the Redis service.
  2. There is no "reentrant" feature when Redis atomic operation SETNX acquires distributed locks.That is, when a thread acquires a lock, other threads fail to acquire the lock, permanently failing, In essence, there is nothing wrong with it, but some business scenarios may require threads to have "reentrant" characteristics. At this time, the SETNX operation is not satisfied with the current needs, and some supporting logic is required for processing, that is, while( true){}, but this method is not elegant, and it is likely to cause the risk of "stuck" in the application system.
  3. When the Redis atomic operation is [after SETNX, before EXPIPR] , the Redis service is down, and the key is not deleted due to a problem with the application service, then the impact will eventually lead to a deadlock thread, that is, there will never be a thread to obtain The lock to the key value (the lock has not been deleted when the TTL is not added, resulting in its permanent existence ).

03 Functional characteristics of Redisson distributed locks

  1. Reentrant lock
  2. Fair lock
  3. Interlock
  4. Red lock
  5. Read-write lock
  6. Semaphore and blocking

04 Redisson distributed lock (reentrant lock) actual combat

Reentrant locks are divided into one-time and re-entrant. As the noun implies, one-time represents that if the current thread can acquire a distributed lock, if it succeeds, acquire it, and if it fails, it will fail permanently. Reentrant represents the current thread When the distributed lock is not acquired, it does not fail immediately, but waits for a period of time to acquire it again.


04::01 Redisson distributed lock (reentrant lock) one-time lock actual combat

code show as below:

    @Autowired
    private RedissonClient redissonClient;
    /**
     * Redission 分布式锁设计(一次性锁)
     * */
    @ApiOperation(value = "Redission 分布式锁设计(一次性锁)",notes = "Redission 分布式锁设计(一次性锁)")
    @ResponseBody
    @PostMapping("/onelock")
    public ResponseBo onelock(String key)  {
        String msgValue = "onelock";
        long startTime = init(msgValue,key);
        //分布式锁名称
        final String lockName = "redissonOneLock-"+key;
        RLock lock = redissonClient.getLock(lockName);
        try{
            //尝试加锁, 上锁后10秒自动解锁
            lock.lock(10,TimeUnit.SECONDS);
            this.info("获取到一次性分布式锁");
            this.info("执行业务逻辑");
            endLog(msgValue,startTime);
            return ResponseBo.ok();
        }catch (Exception e){
            endLogError(msgValue,startTime,e);
            return ResponseBo.error("保存失败" + e.getMessage());
        }finally {
            /**
             * 注:访问共享资源结束后要释放锁
             * */
            if (lock!= null){
                this.info("释放分布式锁");
                lock.unlock();
                //注在某些严格的业务场景下,也可以调用强制释放分布式锁的方法
                //lock.forceUnlock();
            }
        }
    }

test:

Insert picture description here


Insert picture description here

04::02 Redisson distributed lock (reentrant lock) reentrant lock actual combat

code show as below:

    @Autowired
    private RedissonClient redissonClient;
        /**
     * Redission 分布式锁设计(可重入锁)
     * */
    @ApiOperation(value = "Redission 分布式锁设计(可重入锁)",notes = "Redission 分布式锁设计(可重入锁)")
    @ResponseBody
    @PostMapping("/trylock")
    public ResponseBo trylock(String key)  {
        String msgValue = "trylock";
        long startTime = init(msgValue,key);
        //分布式锁名称
        final String lockName = "redissonTryLock-"+key;
        RLock lock = redissonClient.getLock(lockName);
        try{
           //尝试加锁, 最多等待100秒,上锁后10秒自动解锁
            Boolean aBoolean = lock.tryLock(100,10,TimeUnit.SECONDS);
            if (aBoolean){
                this.info("获取到可重入分布式锁");
                this.info("执行业务逻辑");
            }
            endLog(msgValue,startTime);
            return ResponseBo.ok();
        }catch (Exception e){
            endLogError(msgValue,startTime,e);
            return ResponseBo.error("保存失败" + e.getMessage());
        }finally {
            /**
             * 注:访问共享资源结束后要释放锁
             * */
            if (lock!= null){
                this.info("释放分布式锁");
                lock.unlock();
                //注在某些严格的业务场景下,也可以调用强制释放分布式锁的方法
                //lock.forceUnlock();
            }
        }
    }

test:

Insert picture description here


Insert picture description here