search
HomeDatabaseRedisWhat is the implementation principle of redis distributed lock

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
Redis: Beyond SQL - The NoSQL PerspectiveRedis: Beyond SQL - The NoSQL PerspectiveMay 08, 2025 am 12:25 AM

Redis goes beyond SQL databases because of its high performance and flexibility. 1) Redis achieves extremely fast read and write speed through memory storage. 2) It supports a variety of data structures, such as lists and collections, suitable for complex data processing. 3) Single-threaded model simplifies development, but high concurrency may become a bottleneck.

Redis: A Comparison to Traditional Database ServersRedis: A Comparison to Traditional Database ServersMay 07, 2025 am 12:09 AM

Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

Redis: Introduction to a Powerful In-Memory Data StoreRedis: Introduction to a Powerful In-Memory Data StoreMay 06, 2025 am 12:08 AM

Redisisahigh-performancein-memorydatastructurestorethatexcelsinspeedandversatility.1)Itsupportsvariousdatastructureslikestrings,lists,andsets.2)Redisisanin-memorydatabasewithpersistenceoptions,ensuringfastperformanceanddatasafety.3)Itoffersatomicoper

Is Redis Primarily a Database?Is Redis Primarily a Database?May 05, 2025 am 12:07 AM

Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

Redis: Database, Server, or Something Else?Redis: Database, Server, or Something Else?May 04, 2025 am 12:08 AM

Redisisamultifacetedtoolthatservesasadatabase,server,andmore.Itfunctionsasanin-memorydatastructurestore,supportsvariousdatastructures,andcanbeusedasacache,messagebroker,sessionstorage,andfordistributedlocking.

Redis: Unveiling Its Purpose and Key ApplicationsRedis: Unveiling Its Purpose and Key ApplicationsMay 03, 2025 am 12:11 AM

Redisisanopen-source,in-memorydatastructurestoreusedasadatabase,cache,andmessagebroker,excellinginspeedandversatility.Itiswidelyusedforcaching,real-timeanalytics,sessionmanagement,andleaderboardsduetoitssupportforvariousdatastructuresandfastdataacces

Redis: A Guide to Key-Value Data StoresRedis: A Guide to Key-Value Data StoresMay 02, 2025 am 12:10 AM

Redis is an open source memory data structure storage used as a database, cache and message broker, suitable for scenarios where fast response and high concurrency are required. 1.Redis uses memory to store data and provides microsecond read and write speed. 2. It supports a variety of data structures, such as strings, lists, collections, etc. 3. Redis realizes data persistence through RDB and AOF mechanisms. 4. Use single-threaded model and multiplexing technology to handle requests efficiently. 5. Performance optimization strategies include LRU algorithm and cluster mode.

Redis: Caching, Session Management, and MoreRedis: Caching, Session Management, and MoreMay 01, 2025 am 12:03 AM

Redis's functions mainly include cache, session management and other functions: 1) The cache function stores data through memory to improve reading speed, and is suitable for high-frequency access scenarios such as e-commerce websites; 2) The session management function shares session data in a distributed system and automatically cleans it through an expiration time mechanism; 3) Other functions such as publish-subscribe mode, distributed locks and counters, suitable for real-time message push and multi-threaded systems and other scenarios.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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