Distributed - technology zone -Redis Distributed Lock realization of the principle

  In many scenarios, we have to ensure that the final data consistency requires a lot of technical solutions to support, such as distributed transactions, distributed lock. It specifically what is distributed lock, distributed business scenarios in which the lock application, how to achieve a distributed lock it? Distributed Lock today to discuss this topic.

What is the distributed lock

To introduce distributed lock, first mentioned in a distributed lock corresponds to a thread lock, the lock process.

1. Thread lock

  The main method used to code the block lock. When the code uses a method or lock, at the same time only one thread executing the method or the code segments. Only thread-locking effect in the same JVM, because the realization of thread lock is fundamentally rely on shared memory to achieve between threads, such as Synchronized, Lock and so on.

2. The process lock

  In order to control the same operating system in multiple processes to access a shared resource, because the process of independence, each process can not access resources other processes can not be achieved by synchronized such as thread-locking lock process.

3. Distributed Lock

  When multiple processes are not the same system, with multiple processes distributed lock control access to resources.

The origin of distributed lock

  In the case of the conventional single deployment, Java can be used concurrently process related API (such as the synchronized or ReentrantLcok) for exclusive control.

  But after a distributed system, due to the distributed system multi-threaded, multi-process and distributed on different machines, which would make the original stand-alone concurrency control locking strategy fails, in order to solve this problem we need mutual exclusion mechanism to control the JVM of a cross access to shared resources, which is the origin of distributed lock.

  When multiple processes are not the same system, you need to control multiple processes access to resources in a distributed lock.

Distributed Lock features

First, in order to ensure that the distributed lock is available, we at least want to ensure the lock at the same time meet the following four conditions:

  1, mutually exclusive: any given time, only one client to acquire the lock can not have two clients at the same time to get a lock.

  2. Security: lock can only be held by the lock client deleted and can not be deleted by other clients.

  3, deadlock: acquire the lock of the client for some reason (such as down, etc.) fails to release the lock, other client can no longer get into the lock.

  4, a fault-tolerant: when some nodes (Redis nodes, etc.) Down machine, the client still acquire and release locks.

Realization of distributed lock

Distributed Lock There are three general ways:

  1. Database optimistic locking;
  2. Based on a distributed lock ZooKeeper;
  3. Redis-based distributed lock;

Redis achieve Distributed Lock

  Based Redis command: SET key value NX EX max-lock-time

  Complemented here: from version 2.6.12, you can use the set to get the lock, Lua script to release the lock. setnx is laohuangli, set command nx, xx and other parameters, in order to achieve setnx function.

1. Locking

  public class RedisTool {

    private static final String LOCK_SUCCESS = “OK”;

    private static final String SET_IF_NOT_EXIST = “NX”;

    private static final String SET_WITH_EXPIRE_TIME = “PX”;

    / * Try to obtain Distributed Lock 

    @param jedis Redis client 

    @param lockKey lock 

    @param requestId Request ID 

    @param expireTime extended time 

    Whether @return succeed 

    public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) {

       String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);

      if (LOCK_SUCCESS.equals(result)) {

        return true;

      }

      return false;

     }

    }

  jedis.set(String key, String value, String nxxx, String expx, int time)

  The set () method, a total of five parameter:

  The first is the key, when we use the key to lock because the key is unique.

  The second is the value, we preach is requestId, a lot of children's shoes may not understand, there is a key lock is not enough yet, why use value? The reason is that when we talked about the reliability of the above, distributed lock to meet the fourth condition started the trouble should end it, by giving value assigned to requestId, we know that this lock is which request added, and in the unlocked when we can have a basis. requestId can UUID.randomUUID (). toString () method to generate.

  The third is nxxx, we fill this parameter is NX, meaning that SET IF NOT EXIST, that is, when the key is not present, we set operations; if the key already exists, do nothing;

  The fourth is expx, we pass this parameter is PX, meaning that we give this key plus an expired set the specific time decided by the fifth parameter.

  The fifth is the time, and the fourth argument echoes, representatives of key expiration time.

  Overall, the implementation of the above set () method will only lead to two results:

  1. There are currently no lock (key does not exist), then the process of locking operation and a lock setting period, while value represents the locked client.

  2. have been latched, does nothing.

2. Unlock

  public class RedisTool {

    private static final Long RELEASE_SUCCESS = 1L;

    / * Release distributed lock 

    @param jedis Redis client 

    @param lockKey lock 

    @param requestId Request ID 

    Whether @return successfully released

    */

   public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {

    String script = “if redis.call(‘get’, KEYS[1]) == ARGV[1] then return redis.call(‘del’, KEYS[1]) else return 0 end”;

    Object result = jedis.eval(script, Collections.singletonList(lockKey),Collections.singletonList(requestId));

    if (RELEASE_SUCCESS.equals(result)) {

      return true;

    }

    return false;

    }

  }

 

 

 

Guess you like

Origin www.cnblogs.com/liboware/p/11921759.html