【redisson】分布式锁实现

使用Redisson实现分布式锁

依赖

1
2
3
4
5
6
<!-- 分布式锁Redisson -->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.13.6</version>
</dependency>

配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import org.redisson.Redisson;  
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RedissonConfig {

@Value("${spring.redis.hostName}")
private String redisHost;

@Value("${spring.redis.password}")
private String password;

private int port = 6379;

@Bean
public RedissonClient getRedisson() {
Config config = new Config();
config.useSingleServer().setAddress("redis://" + redisHost + ":" + port).setPassword(password);
config.setCodec(new JsonJacksonCodec());
return Redisson.create(config);
}
}

使用测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Resource
private RedissonClient redissonClient;

@Test
public void redissonLockTest() {
RLock rLock = redissonClient.getLock("MYLOCK1");
try {
boolean isrLock = rLock.tryLock(5, TimeUnit.SECONDS);
System.out.println("sleep11++++++" + isrLock);
if (isrLock) {
Thread.sleep(5000);
System.out.println("=====sleep11 finish!!!");
}

} catch (Exception e) {
e.printStackTrace();
rLock.unlock();
}
}

经测试Redisson锁会自动续期,如未手动调用unlock解锁,线程结束后需要等过期才会释放锁。

竞争测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
@Test
public void redissonLockTest() {
RLock rLock = redissonClient.getLock("MYLOCK1");
try {
boolean isrLock = rLock.tryLock(5, TimeUnit.SECONDS);
System.out.println("sleep11++++++" + isrLock);
if (isrLock) {
Thread.sleep(15000);
System.out.println("lock is still here but i unlock it");
rLock.unlock();
Thread.sleep(15000);
System.out.println("=====sleep11 finish!!!");
}

} catch (Exception e) {
e.printStackTrace();
rLock.unlock();
}
}

@Test
public void redissonLockTest2() {
RLock rLock = redissonClient.getLock("MYLOCK1");
try {
boolean isrLock = rLock.tryLock(5, TimeUnit.SECONDS);
System.out.println("sleep22++++++" + isrLock);
while (!isrLock) {
isrLock = rLock.tryLock(10, TimeUnit.SECONDS);
if (isrLock) {
System.out.println("i have lock!");
Thread.sleep(5000);
System.out.println("=====sleep22 finish!!!");
} else {
System.out.println("i have no lock");
}
}
} catch (Exception e) {
e.printStackTrace();
rLock.unlock();
}
}