Home  >  Article  >  Database  >  What is the implementation principle of redis distributed lock

What is the implementation principle of redis distributed lock

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-06-23 11:57:193381browse

With the help of the command setnx(key, value) in redis, if the key does not exist, it will be added, and if it exists, nothing will be done. If multiple clients send the setnx command at the same time, only one client can succeed and return 1 (true); other clients return 0 (false).

What is the implementation principle of redis distributed lock

The operating environment of this tutorial: Windows 7 system, Redis version 5.0.10, DELL G3 computer.

Implementation of distributed locks

With the needs of business development, the original single-machine deployed system has evolved into a distributed cluster system. Since the distributed system is multi-threaded, multi-process and distributed, On different machines, this will invalidate the concurrency control lock strategy in the original single-machine deployment. The simple Java API cannot provide distributed lock capabilities. In order to solve this problem, a cross-JVM mutual exclusion mechanism is needed to control access to shared resources. This is the problem that distributed locks need to solve!

Mainstream implementation of distributed locks:

  • Implementing distributed locks based on database

  • Based on cache (Redis, etc.)

  • Based on Zookeeper

Here, we implement distributed locks based on redis.

Basic implementation

With the help of the command setnx(key, value) in redis, if the key does not exist, it will be added, and if it exists, nothing will be done. If multiple clients send the setnx command at the same time, only one client can succeed and return 1 (true); other clients return 0 (false).

What is the implementation principle of redis distributed lock

Mainly use the Redis Setnx command

When the specified key does not exist, set the specified value for the key

Set successfully and return 1 . The setting fails and returns 0

redis> EXISTS job                # job 不存在

(integer) 0

 

redis> SETNX job "programmer"    # job 设置成功

(integer) 1

 

redis> SETNX job "code-farmer"   # 尝试覆盖 job ,失败

(integer) 0

 

redis> GET job                   # 没有被覆盖

"programmer"

java code

	public void testLock() {

		// 执行redis的setnx命令

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

		Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 5, TimeUnit.SECONDS);

 

		// 判断是否拿到锁

		if (lock) {

			// 执行业务逻辑代码

			// ...

 

			// 释放锁资源 (保证获取值和删除操作的原子性) LUA脚本保证删除的原子性

			String script = "if redis.call('get', KEYS[1]) == ARGV[1] then
 return redis.call('del', KEYS[1]) else return 0 end";

			this.redisTemplate.execute(new DefaultRedisScript<>(script), 
Arrays.asList("lock"), Arrays.asList(uuid));

//			if (StrUtil.equals(uuid,redisTemplate.opsForValue().get("lock"))){

//				redisTemplate.delete("lock");

//			}

		} else {

			// 其他请求尝试获取锁

			testLock();

		}

	}

In order to ensure that the distributed lock is available, we must at least ensure that the lock implementation meets the following four conditions at the same time:

Mutual exclusion sex. At any time, only one client can hold the lock.

No deadlock will occur. Even if a client crashes while holding the lock without actively unlocking it, it is guaranteed that other clients can subsequently lock it.

The trouble should end it. The locking and unlocking must be done by the same client. The client itself cannot unlock the lock added by others.

Recommended related tutorials: Redis Tutorial

The above is the detailed content of What is the implementation principle of redis distributed lock. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn