SpringBoot集成Redisson实现简单Redis分布式锁
1. Maven添加Redisson依赖
pom.xml中添加如下内容:
<!-- 集成redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 集成 redisson -->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.11.2</version>
</dependency>
2. 配置文件application.properties添加配置
#################redis基础配置#################
spring.redis.database=5
spring.redis.host=127.0.0.1
spring.redis.port=6379
#spring.redis.password=
spring.redis.timeout=3000
#spring.redis.redisson.config=classpath:redisson.yaml
详细配置可参考:
https://github.com/redisson/redisson/blob/master/redisson-spring-boot-starter/README.md
3. 添加工具类:RedissLockUtil.java
import java.util.concurrent.TimeUnit;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
-
redis分布式锁帮助类
-
@author huxiaojie
*/
@Component
public class RedissLockUtil {@Autowired
private RedissonClient redissonClient;/**
- 加锁
- @param lockKey
- @return
*/
public RLock lock(String lockKey) {
RLock lock = redissonClient.getLock(lockKey);
lock.unlock();
return lock;
}
/**
- 释放锁
- @param lockKey
*/
public void unlock(String lockKey) {
RLock lock = redissonClient.getLock(lockKey);
lock.unlock();
}
/**
- 释放锁
- @param lock
*/
public void unlock(RLock lock) {
lock.unlock();
}
/**
- 带超时的锁
- @param lockKey
- @param timeout 超时时间 单位:秒
*/
public RLock lock(String lockKey, int timeout) {
RLock lock = redissonClient.getLock(lockKey);
lock.lock(timeout, TimeUnit.SECONDS);
return lock;
}
/**
- 带超时的锁
- @param lockKey
- @param unit 时间单位
- @param timeout 超时时间
*/
public RLock lock(String lockKey, TimeUnit unit ,int timeout) {
RLock lock = redissonClient.getLock(lockKey);
lock.lock(timeout, unit);
return lock;
}
/**
- 尝试获取锁
- @param lockKey
- @param waitTime 最多等待时间
- @param leaseTime 上锁后自动释放锁时间
- @return
*/
public boolean tryLock(String lockKey, int waitTime, int leaseTime) {
RLock lock = redissonClient.getLock(lockKey);
try {
return lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
} catch (InterruptedException e) {
return false;
}
}
/**
- 尝试获取锁
- @param lockKey
- @param unit 时间单位
- @param waitTime 最多等待时间
- @param leaseTime 上锁后自动释放锁时间
- @return
*/
public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
RLock lock = redissonClient.getLock(lockKey);
try {
return lock.tryLock(waitTime, leaseTime, unit);
} catch (InterruptedException e) {
return false;
}
}
}
4. 使用Demo
A.模式一
redissLockUtil.lock(key, 10); //直接加锁,获取不到锁则一直等待获取锁,防止死锁,10秒后自动释放锁
… //获得锁之后可以进行相应的处理
redissLockUtil.unlock(key); //解锁
B.模式二
boolean isGetLock = redissLockUtil.tryLock(key, TimeUnit.SECONDS, 5, 10); //尝试获取锁,等待5秒,自己获得锁后一直不解锁则10秒后自动解锁
if (isGetLock) {
… //获得锁之后可以进行相应的处理
//redissLockUtil.unlock(key); //也可主动解锁
}