Example analysis of the implementation principle of redis distributed lock
First of all, in order to ensure that distributed locks are available, we must at least ensure that the lock implementation meets the following four conditions at the same time:
1. Mutual exclusivity. At any time, only one client can hold the lock.
2. 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.
3. Fault-tolerant. As long as most Redis nodes are running normally, the client can lock and unlock.
4. To untie the bell, you must also tie the bell. The locking and unlocking must be done by the same client. The client itself cannot unlock the lock added by others.
The following is the code implementation. First, we need to introduce the Jedis
open source component through Maven, and add the following code to the pom.xml
file:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.1.0</version> </dependency>
Distributed lock implementation code, DistributedLock.java
import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.Transaction; import redis.clients.jedis.exceptions.JedisException; import java.util.List; import java.util.UUID; /** * @author swadian * @date 2022/3/4 * @Version 1.0 * @describetion Redis分布式锁原理 */ public class DistributedLock { //redis连接池 private static JedisPool jedisPool; static { JedisPoolConfig config = new JedisPoolConfig(); // 设置最大连接数 config.setMaxTotal(200); // 设置最大空闲数 config.setMaxIdle(8); // 设置最大等待时间 config.setMaxWaitMillis(1000 * 100); // 在borrow一个jedis实例时,是否需要验证,若为true,则所有jedis实例均是可用的 config.setTestOnBorrow(true); jedisPool = new JedisPool(config, "192.168.3.27", 6379, 3000); } /** * 加锁 * @param lockName 锁的key * @param acquireTimeout 获取锁的超时时间 * @param timeout 锁的超时时间 * @return 锁标识 * Redis Setnx(SET if Not eXists) 命令在指定的 key 不存在时,为 key 设置指定的值。 * 设置成功,返回 1 。 设置失败,返回 0 。 */ public String lockWithTimeout(String lockName, long acquireTimeout, long timeout) { Jedis jedis = null; String retIdentifier = null; try { // 获取连接 jedis = jedisPool.getResource(); // value值->随机生成一个String String identifier = UUID.randomUUID().toString(); // key值->即锁名 String lockKey = "lock:" + lockName; // 超时时间->上锁后超过此时间则自动释放锁 毫秒转成->秒 int lockExpire = (int) (timeout / 1000); // 获取锁的超时时间->超过这个时间则放弃获取锁 long end = System.currentTimeMillis() + acquireTimeout; while (System.currentTimeMillis() < end) { //在获取锁时间内 if (jedis.setnx(lockKey, identifier) == 1) {//关键:设置锁 jedis.expire(lockKey, lockExpire); // 返回value值,用于释放锁时间确认 retIdentifier = identifier; return retIdentifier; } // ttl以秒为单位返回 key 的剩余过期时间,返回-1代表key没有设置超时时间,为key设置一个超时时间 if (jedis.ttl(lockKey) == -1) { jedis.expire(lockKey, lockExpire); } try { Thread.sleep(10); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } catch (JedisException e) { e.printStackTrace(); } finally { if (jedis != null) { jedis.close(); } } return retIdentifier; } /** * 释放锁 * @param lockName 锁的key * @param identifier 释放锁的标识 * @return */ public boolean releaseLock(String lockName, String identifier) { Jedis jedis = null; String lockKey = "lock:" + lockName; boolean retFlag = false; try { jedis = jedisPool.getResource(); while (true) { // 监视lock,准备开始redis事务 jedis.watch(lockKey); // 通过前面返回的value值判断是不是该锁,若是该锁,则删除,释放锁 if (identifier.equals(jedis.get(lockKey))) { Transaction transaction = jedis.multi();//开启redis事务 transaction.del(lockKey); List<Object> results = transaction.exec();//提交redis事务 if (results == null) {//提交失败 continue;//继续循环 } retFlag = true;//提交成功 } jedis.unwatch();//解除监控 break; } } catch (JedisException e) { e.printStackTrace(); } finally { if (jedis != null) { jedis.close(); } } return retFlag; } }
In order to verify it, we create the SkillService.java business class
import lombok.extern.slf4j.Slf4j; @Slf4j public class SkillService { final DistributedLock lock = new DistributedLock(); public static final String LOCK_KEY = "lock_resource"; int n = 500; /** * 线程业务方法 */ public void seckill() { // 返回锁的value值,供释放锁时候进行判断 String identifier = lock.lockWithTimeout(LOCK_KEY, 5000, 1000); log.info("线程:"+Thread.currentThread().getName() + "获得了锁"); log.info("剩余数量:{}",--n); lock.releaseLock(LOCK_KEY, identifier); } }
If the @Slf4j log cannot be found, inpom.xml
Add the following code to the file:
<!--@Slf4j日志依赖组件--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
Edit a test class TestLock.java
/** * @author swadian * @date 2022/3/4 * @Version 1.0 */ public class TestLock { public static void main(String[] args) { SkillService service = new SkillService(); for (int i = 10; i < 60; i++) { //开50个线程 SkillThread skillThread = new SkillThread(service, "skillThread->" + i); skillThread.start(); } } } class SkillThread extends Thread { private SkillService skillService; public SkillThread(SkillService skillService, String skillThreadName) { super(skillThreadName); this.skillService = skillService; } @Override public void run() { skillService.seckill(); } }
The test results show that the remaining numbers after locking are all sequential and serial, 499,498,497...
We modify the SkillService.java business class and comment out the locking logic
@Slf4j public class SkillService { final DistributedLock lock = new DistributedLock(); public static final String LOCK_KEY = "lock_resource"; int n = 500; /** * 线程业务方法 */ public void seckill() { // 返回锁的value值,供释放锁时候进行判断 //String identifier = lock.lockWithTimeout(LOCK_KEY, 5000, 1000); log.info("线程:"+Thread.currentThread().getName() + "获得了锁"); log.info("剩余数量:{}",--n); //lock.releaseLock(LOCK_KEY, identifier); } }
Re-execute the test and after commenting out the locking logic, the remaining quantities are all messed up In sequence, 472,454,452...
The above is the detailed content of Example analysis of the implementation principle of redis distributed lock. For more information, please follow other related articles on the PHP Chinese website!

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis improves application performance and scalability by caching data, implementing distributed locking and data persistence. 1) Cache data: Use Redis to cache frequently accessed data to improve data access speed. 2) Distributed lock: Use Redis to implement distributed locks to ensure the security of operation in a distributed environment. 3) Data persistence: Ensure data security through RDB and AOF mechanisms to prevent data loss.

Redis's data model and structure include five main types: 1. String: used to store text or binary data, and supports atomic operations. 2. List: Ordered elements collection, suitable for queues and stacks. 3. Set: Unordered unique elements set, supporting set operation. 4. Ordered Set (SortedSet): A unique set of elements with scores, suitable for rankings. 5. Hash table (Hash): a collection of key-value pairs, suitable for storing objects.

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.

Redis is a powerful database solution because it provides fast performance, rich data structures, high availability and scalability, persistence capabilities, and a wide range of ecosystem support. 1) Extremely fast performance: Redis's data is stored in memory and has extremely fast read and write speeds, suitable for high concurrency and low latency applications. 2) Rich data structure: supports multiple data types, such as lists, collections, etc., which are suitable for a variety of scenarios. 3) High availability and scalability: supports master-slave replication and cluster mode to achieve high availability and horizontal scalability. 4) Persistence and data security: Data persistence is achieved through RDB and AOF to ensure data integrity and reliability. 5) Wide ecosystem and community support: with a huge ecosystem and active community,

Key features of Redis include speed, flexibility and rich data structure support. 1) Speed: Redis is an in-memory database, and read and write operations are almost instantaneous, suitable for cache and session management. 2) Flexibility: Supports multiple data structures, such as strings, lists, collections, etc., which are suitable for complex data processing. 3) Data structure support: provides strings, lists, collections, hash tables, etc., which are suitable for different business needs.

The core function of Redis is a high-performance in-memory data storage and processing system. 1) High-speed data access: Redis stores data in memory and provides microsecond-level read and write speed. 2) Rich data structure: supports strings, lists, collections, etc., and adapts to a variety of application scenarios. 3) Persistence: Persist data to disk through RDB and AOF. 4) Publish subscription: Can be used in message queues or real-time communication systems.

Redis supports a variety of data structures, including: 1. String, suitable for storing single-value data; 2. List, suitable for queues and stacks; 3. Set, used for storing non-duplicate data; 4. Ordered Set, suitable for ranking lists and priority queues; 5. Hash table, suitable for storing object or structured data.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

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.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6
Visual web development tools