The most basic content of Redisson distributed lock

1. Introduction

1. Concept

Official website address:

https://redisson.org

GitHub address:

https://github.com/redisson/redisson

Redisson is a Java in-memory data grid (In-Memory Data Grid) implemented on the basis of Redis. It not only provides a series of distributed common Java objects, but also provides many distributed services.

The purpose of Redisson is to promote users' separation of concerns about Redis (Separation of Concern), so that users can focus more on processing business logic.
A distributed tool based on Redis, with basic distributed objects and advanced and abstract distributed services, brings solutions to most distributed problems for every programmer who tries to reinvent the distributed wheel.

Redisson is a Java in-memory data grid (In-Memory Data Grid) implemented on the basis of Redis. It not only provides a series of distributed common Java objects, but also provides many distributed services, including the implementation of various distributed locks.

insert image description here

2. Difference

What is the difference between Redisson, Jedis and Lettuce? Not Lei Feng and Lei Feng Tower

The difference between Redisson and the two is like using a mouse to operate a graphical interface, and the other uses a command line to operate files. Redisson is a higher-level abstraction, and Jedis and Lettuce are encapsulations of Redis commands.

Jedis is a toolkit officially launched by Redis for connecting Redis clients through Java. It provides various Redis command support.
Lettuce is an extensible thread-safe Redis client. The communication framework is based on Netty and supports advanced Redis features. , such as sentinels, clusters, pipelines, auto-reconnect and the Redis data model. Starting with Spring Boot 2.x, Lettuce has replaced Jedis as the preferred Redis client.
Redisson is built on the basis of Redis, and the communication is based on the comprehensive and new middleware of Netty. Jedis, the best template for using Redis in enterprise-level development,
encapsulates Redis commands. Lettuce further has a richer API and also supports clusters. and other modes. But both of them stop at the end, and only give you the scaffolding to operate the Redis database, while Redisson has established a mature distributed solution based on Redis, Lua and Netty, and even a tool set officially recommended by redis.

2. Quick start

1、pom.xml

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.13.6</version>
</dependency>

2. Configure the Redisson client

@Configuration
public class RedisConfig {
    
    
    @Bean
    public RedissonClient redissonClient() {
    
    
        // 配置类
        Config config = new Config();
        // 添加redis地址,这里添加了单点的地址,也可以使用config.useClusterServers()添加集群地址 
        config.useSingleServer().setAddress("redis://192.168.150.101:6379").setPassowrd("123321");
        // 创建客户端
        return Redisson.create(config);
    }
}

3. Use Redisson's distributed lock

@Resource
private RedissonClient redissonClient;
@Test
void testRedisson() throws InterruptedException {
    
    
    // 获取锁(可重入),指定锁的名称
    RLock lock = redissonClient.getLock("anyLock");
    // 尝试获取锁,参数分别是:获取锁的最大等待时间(期间会重试),锁自动释放时间,时间单位
    boolean isLock = lock.tryLock(1, 10, TimeUnit.SECONDS);
    // 判断释放获取成功
    if (isLock) {
    
    
        try {
    
    
            System.out.println("执行业务");
        } finally {
    
    
            // 释放锁
            lock.unlock();
        }
    }
}

3. Principle

What is Lua scripting?
Lua script is a lightweight and compact language that has been built into redis. Its execution is run through the eval /evalsha command of redis, and the operation is encapsulated into a Lua script. In any case, it is an atomic operation executed at one time.

insert image description here insert image description here

Lua script to acquire the lock:

local key = KEYS[1]; -- 锁的key
local threadId = ARGV[1]; -- 线程唯一标识
local releaseTime = ARGV[2]; -- 锁的自动释放时间
-- 判断是否存在
if(redis.call('exists', key) == 0) then
    -- 不存在, 获取锁
    redis.call('hset', key, threadId, '1'); 
    -- 设置有效期
    redis.call('expire', key, releaseTime); 
    return 1; -- 返回结果
end;
-- 锁已经存在,判断threadId是否是自己
if(redis.call('hexists', key, threadId) == 1) then
    -- 不存在, 获取锁,重入次数+1
    redis.call('hincrby', key, threadId, '1'); 
    -- 设置有效期
    redis.call('expire', key, releaseTime); 
    return 1; -- 返回结果
end;
return 0; -- 代码走到这里,说明获取锁的不是自己,获取锁失败

Lua script to release the lock:

local key = KEYS[1]; -- 锁的key
local threadId = ARGV[1]; -- 线程唯一标识
local releaseTime = ARGV[2]; -- 锁的自动释放时间
-- 判断当前锁是否还是被自己持有
if (redis.call('HEXISTS', key, threadId) == 0) then
    return nil; -- 如果已经不是自己,则直接返回
end;
-- 是自己的锁,则重入次数-1
local count = redis.call('HINCRBY', key, threadId, -1);
-- 判断是否重入次数是否已经为0 
if (count > 0) then
    -- 大于0说明不能释放锁,重置有效期然后返回
    redis.call('EXPIRE', key, releaseTime);
    return nil;
else  -- 等于0说明可以释放锁,直接删除
    redis.call('DEL', key);
    return nil;
end;

insert image description here

Redisson distributed lock principle:

  • Reentrant: use hash structure to record thread id and reentry times
  • Retryable: Use the semaphore and PubSub functions to implement the retry mechanism for waiting, waking up, and failing to acquire locks
  • Timeout renewal: use watchDog to reset the timeout period at regular intervals (releaseTime / 3)

4. Redis distributed master-slave consistency

1) Non-reentrant Redis distributed lock:

  • Principle: use the mutual exclusion of setnx; use ex to avoid deadlock; judge the thread mark when releasing the lock
  • Defects: non-reentrant, unable to retry, lock timeout failure

2) Reentrant Redis distributed lock:

  • Principle: Use the hash structure to record thread marking and reentry times; use watchDog to extend the lock time; use semaphores to control lock retry waiting
  • Defect: lock failure caused by redis downtime
    3) Redisson's multiLock:
  • Principle: Multiple independent Redis nodes must obtain reentrant locks on all nodes to obtain locks successfully
  • Defects: high operation and maintenance costs, complex implementation

Guess you like

Origin blog.csdn.net/weixin_44624117/article/details/131467229