Why do not you redis Distributed Lock? Because you did not see this article

I. Introduction

redis in a wide range of distributed applications, this article is focused on the contents of the interview of the Internet, the reader needs to know at least why you need a distributed lock, realization of the principle of distributed locks, locks distributed application scenarios encountered when using distributed lock ? What is the problem you how to solve, if the reader can grasp the above questions, then face questions on this road, you will basically get away with it;

Distributed background two locks

Distributed Lock corresponding to a plurality of applications, each application may be the same data processing, if a plurality of applications performed by a repeat operation, data inconsistency occurs, data duplication, then DLM application I was born, and usually you can be understood as a multi-thread synchronized

Scene Three distributed application locks

  1. Multiple machines can perform a task, if the task can only be performed to limit a machine can not be performed repeatedly, you can do a distributed lock mark
  2. Spike scene, demanding concurrency, it can only be with a commodity grab a user, you can use the Distributed Lock achieve
  3. Sensitive data such as the amount of modification, at the same time only one person to operate, if two individuals also modify the amount, a sum plus a reduction, in order to prevent simultaneous operation caused by inconsistent data, you can use the Distributed Lock achieve

Four Distributed Lock implementation

4.1 Distributed Lock implementation

  1. Based on implementation of distributed database lock
  2. Based caching (redis, memcached, tair) implement a distributed lock
  3. Based achieve Zookeeper distributed lock

4.2 use distributed lock principle

Each application needs to acquire a lock, holding the lock application to operate on the data, ensure that only one application can operate on data at the same time sensitive data operations;

4.3 Distributed Lock implementation process

The basic realization of ideas :

redis distributed implementation is based on the command setnx key value, which means if the key does not exist, create the key, which ensures that the redis only one key, so the application of who should get the key, whoever got the permission to lock; then the business logic it is finished you will need to use the del key delete key, shows the release lock;

There is a problem :

If a business logic is finished, the program appears abnormal, the lock will always exist, has not been released, other applications will not get the lock, then it will cause 死锁problems;

Improve the way :

After get the lock, lock coupled to an expiration time, i.e. expire key seconds instruction; case avoids deadlock problem, but due to the different service logic execution time, the expiration time is provided also a problem, it is usually distributed lock 不能应用于业务逻辑执行较长的程序;

Problem :

Since redis Each instruction atomicity operations, but due to expire and are setnx 2 instructions, if the program appears after performing setnx problem expire unimplemented instruction can cause 死锁problems;

To solve the problem :

redis2.8 version introduced after the instruction set key value [EX seconds] [PX milliseconds] [NX|XX], and the instruction can be executed setnx expire simultaneously, so to solve the deadlock problem;

The list of parameters to explain

  • EX seconds: set the expiration time, in seconds.
  • PX milliseconds: set the expiration time, in milliseconds
  • NX: key setting value does not exist
  • XX: Set key value exists

Use jedis client implements a distributed lock mode

public boolean lock(Jedis jedis,String key,String val,int expireTime){
    String lock = jedis.set(key, val, "NX", "PX",
            expireTime);
    return "OK".equals(lock);
}

Solutions are not about to acquire a lock :

Direct throw an exception to allow customers to retry

You can use delay queue

Five questions distributed lock timeout

Problem :

If between the lock and release the lock, business logic execution time is too long, leading to lock timeout limit exceeded, there will be a lock expires problem; in other words, is the first business application execution, resulting in the lock expired; the first at this time, the application can obtain two sets of locks, for performing operations, when the first lock release application, a second application when performing operations to obtain a third application performing lock operations, resulting in the implementation process, there will be 2 while performing the application business logic;

Solutions :

It appears in the release of the lock when the problem that each application can release the lock, which can cause an application lock release application lock problem 2, in other words, a lot of people holding hands keys are common, can be open the same door; to avoid this problem, that is, 1 application can only release the lock on an application, the application can only release the lock 2 on the 2 applications, you need to release the lock for identity verification; when the key is locked due the only, but the value may be different, depending on the identity of the unique identification value, a random number is a good choice:

String value = UUID.randomUUID().toString();

Taking into account the value matches with a checksum operation del not, we need to use Lua scripts atomicity execute multiple instructions;

jedis release the lock implementations :

public void unlock(Jedis jedis,String key,String value) {
        String script_command = "if redis.call('get',KEYS[1]) == ARGV[1] then " +
                "return redis.call('del',KEYS[1]) else return 0 end";
        // 解锁
        jedis.eval(script_command, Collections.singletonList(key), Collections.singletonList(value));
        
    }

Six Portal

If we asked you what is distributed lock, put a few articles like he hit

https://juejin.im/post/5cc165816fb9a03202221dd5

https://www.jianshu.com/p/268e5d4ce045

Guess you like

Origin www.cnblogs.com/zszxz/p/12488852.html