search
HomeDatabaseRedisAn article explaining in detail how to use Redis to implement distributed locks

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:脚本之家. If there is any infringement, please contact admin@php.cn delete
es和redis区别es和redis区别Jul 06, 2019 pm 01:45 PM

Redis是现在最热门的key-value数据库,Redis的最大特点是key-value存储所带来的简单和高性能;相较于MongoDB和Redis,晚一年发布的ES可能知名度要低一些,ES的特点是搜索,ES是围绕搜索设计的。

一起来聊聊Redis有什么优势和特点一起来聊聊Redis有什么优势和特点May 16, 2022 pm 06:04 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了关于redis的一些优势和特点,Redis 是一个开源的使用ANSI C语言编写、遵守 BSD 协议、支持网络、可基于内存、分布式存储数据库,下面一起来看一下,希望对大家有帮助。

实例详解Redis Cluster集群收缩主从节点实例详解Redis Cluster集群收缩主从节点Apr 21, 2022 pm 06:23 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis Cluster集群收缩主从节点的相关问题,包括了Cluster集群收缩概念、将6390主节点从集群中收缩、验证数据迁移过程是否导致数据异常等,希望对大家有帮助。

Redis实现排行榜及相同积分按时间排序功能的实现Redis实现排行榜及相同积分按时间排序功能的实现Aug 22, 2022 pm 05:51 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis实现排行榜及相同积分按时间排序,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,希望对大家有帮助。

详细解析Redis中命令的原子性详细解析Redis中命令的原子性Jun 01, 2022 am 11:58 AM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了关于原子操作中命令原子性的相关问题,包括了处理并发的方案、编程模型、多IO线程以及单命令的相关内容,下面一起看一下,希望对大家有帮助。

一文搞懂redis的bitmap一文搞懂redis的bitmapApr 27, 2022 pm 07:48 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了bitmap问题,Redis 为我们提供了位图这一数据结构,位图数据结构其实并不是一个全新的玩意,我们可以简单的认为就是个数组,只是里面的内容只能为0或1而已,希望对大家有帮助。

实例详解Redis实现排行榜及相同积分按时间排序功能的实现实例详解Redis实现排行榜及相同积分按时间排序功能的实现Aug 26, 2022 pm 02:09 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis实现排行榜及相同积分按时间排序,本文通过实例代码给大家介绍的非常详细,下面一起来看一下,希望对大家有帮助。

一起聊聊Redis实现秒杀的问题一起聊聊Redis实现秒杀的问题May 27, 2022 am 11:40 AM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了关于实现秒杀的相关内容,包括了秒杀逻辑、存在的链接超时、超卖和库存遗留的问题,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor