Home  >  Article  >  Database  >  An article explaining in detail how to use Redis to implement distributed locks

An article explaining in detail how to use Redis to implement distributed locks

WBOY
WBOYforward
2022-09-07 14:18:182101browse

Recommended learning: Redis video tutorial

1. What is a distributed lock

When we write multi-threaded code, different threads may compete for resources. In order to avoid errors caused by resource competition, we will lock the resources. Only the thread that has obtained the lock can continue to execute.

The lock in the process is essentially a variable in the memory. When a thread performs an operation to apply for a lock, if it can successfully set the value of the variable representing the lock to 1, it means that the lock has been obtained. Others The thread will block when it wants to obtain the lock. After the thread owning the lock completes the operation, it sets the value of the lock to 0, which means the lock is released.

What we are talking about above is the lock between different threads in the process of a server. This lock is placed in the memory, and for distributed applications Say, different applications (processes or threads) are deployed on different servers, so locks cannot be represented by variables in memory.

Since the lock can be represented by the shared memory space on a server, for distributed applications, a shared storage system can be used to store a shared lock. This is a distributed lock. As an in-memory database, Redis executes very quickly and is very suitable as a shared storage system for implementing distributed locks.

2. Use Redis to implement distributed locks

For a lock, there are actually only two operations, locking and releasing the lock. Let’s look at it below. Let’s see how to achieve it through Redis?

2.1 The setnx

command of locking

#Redis will determine whether the key value exists. If it exists, nothing will be done. operation, and returns 0. If it does not exist, create and assign a value, and return 1, so we can execute setnx to set a value for a representative lock key. If the setting is successful, it means the lock is obtained. If it fails, Unable to acquire lock.

# 使用key为lock来表示一个锁
setnx lock 1

2.2 Release the lock

After the operation is performed, when you want to release the lock, directly change the key value in Redislock Just delete it, so that other processes can reset and obtain the lock through the setnx command.

# 释放锁
del lock

Through the above two commands, we have implemented a simple distributed lock, but there is a problem here: if a process is locked through the setnx command, after executing the specific If the operation goes wrong and there is no way to release the lock in time, then other processes will not be able to obtain the lock, and the system will not be able to continue execution. The way to solve this problem is to set a validity period for the lock, and after this validity period, the lock will be automatically released.

2.3 Set the validity period for the lock

It is very simple to set the validity period for the lock. Just use the expire command of Redis , such as:

# 加锁
setnx lock 1 
# 给锁设置10s有效期
expire lock 10

However, another problem arises now. If after setting the lock, the process hangs before executing the expire command, then expire If the execution is not successful, the lock has not been released, so we must ensure that the above two commands are executed together. How to ensure this?

There are two methods, one is a script written in LUA language, and the other is using the set command of Redis, When the set command is followed by the nx parameter, the execution effect is consistent with setnx, and the set command can be followed by the ex parameter. Set the expiration time, so we can use the set command to merge the setnx and expire together, so that the atomicity of execution can be guaranteed.

# 判断是否键值是否存在,ex后面跟着的是键值的有效期,10s
set lock 1 nx ex 10

Having solved the problem of effective locks, now let’s look at another problem.

As shown in the picture above, there are now processes on three different servers: A, B, C To perform an operation, you need to obtain a lock and release the lock after execution.

现在的情况是进程A执行第2步时卡顿了(上面绿色区域所示),且时间超出了锁有效期,所以进程A设置的锁自动释放了,这时候进程B获得了锁,并开始执行操作,但由于进程A只是卡顿了而已,所以会继续执行的时候,在第3步的时候会手动释放锁,但是这个时候,锁由线程B所拥有,也就是说进程A删除的不是自己的锁,而进程B的锁,这时候进程B还没执行完,但锁被释放后,进程C可以加锁,也就是说由于进程A卡顿释放错了锁,导致进程B和进程C可以同时获得锁

怎么避免这种情况呢?如何区分其他进程的锁,避免删除其他进程的锁呢?答案就是每个进程在加锁的时候,给锁设置一个唯一值,并在释放锁的时候,判断是不是自己设置的锁。

2.4 给锁设置唯一值

给锁设置唯一值的时候,一样是使用set命令,唯一的不同是将键值1改为一个随机生成的唯一值,比如uuid。

 # rand_uid表示唯一id
set lock rand_id nx ex 10

当锁里的值由进程设置后,释放锁的时候,就需要判断锁是不是自己的,步骤如下:

  • 通过Redisget命令获得锁的值
  • 根据获得的值,判断锁是不是自己设置的
  • 如果是,通过del命令释放锁。

此时我们看到,释放锁需要执行三个操作,如果三个操作依次执行的话,是没有办法保证原子性的,比如进程A在执行到第2步后,准备开始执行del命令时,而锁由时有效期到了,被自动释放了,并被其他服务器上的进程B获得锁,但这时候线程A执行del还是把线程B的锁给删掉了。

解决这个问题的办法就是保证上述三个操作执行的原子性,即在执行释放锁的三个操作中,其他进程不可以获得锁,想要做到这一点,需要使用到LUA脚本。

2.5 通过LUA脚本实现释放锁的原子性

Redis支持LUA脚本,LUA脚里的代码执行的时候,其他客户端的请求不会被执行,这样可以保证原子性操作,所以我们可以使用下面脚本进行锁的释放:

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

将上述脚本保存为脚本后,可以调用Redis客户端命令redis-cli来执行,如下:

# lock为key,rand_id表示key里保存的值
redis-cli --eval unlock.lua lock , rand_id

推荐学习:Redis视频教程

The above is the detailed content of An article explaining in detail how to use Redis to implement distributed locks. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete