Spring Boot中使用Redis实现分布式锁
在Spring Boot中使用Redis实现分布式锁,可以避免多个进程/线程同时访问共享资源的问题,从而确保系统的数据安全性。
下面是使用Redis实现分布式锁的基本步骤:
一、引入Redis依赖
在pom.xml中添加Redis依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二、创建Redis连接池
在application.properties中配置Redis连接池:
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0
spring.redis.timeout=30000
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=10000
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
可以通过在Spring Boot的配置文件中添加以下内容来配置Redis连接池:
spring:
redis:
host: localhost # Redis服务器地址
port: 6379 # Redis服务器端口号
password: # Redis服务器密码,如果没有密码可以不填
database: 0 # Redis数据库编号,从0到15,默认为0
lettuce:
pool:
max-active: 8 # 连接池最大连接数,默认为8
max-idle: 8 # 连接池中最大的空闲连接数,默认为8
min-idle: 0 # 连接池中最小的空闲连接数,默认为0
max-wait: -1ms # 连接池最大等待时间,-1表示无限等待,默认为-1ms
以上配置文件中的属性解释如下:
- spring.redis.host:Redis服务器地址,可以是IP地址或域名。
- spring.redis.port:Redis服务器端口号。
- spring.redis.password:Redis服务器密码,如果没有密码可以不填。
- spring.redis.database:Redis数据库编号,从0到15,默认为0。
- spring.redis.lettuce.pool.max-active:连接池最大连接数,默认为8。
- spring.redis.lettuce.pool.max-idle:连接池中最大的空闲连接数,默认为8。
- spring.redis.lettuce.pool.min-idle:连接池中最小的空闲连接数,默认为0。
- spring.redis.lettuce.pool.max-wait:连接池最大等待时间,-1表示无限等待,默认为-1ms。
需要注意的是,以上配置中的lettuce是指使用Lettuce作为Redis客户端的实现,Lettuce是一个高性能、线程安全的Redis客户端,相较于Jedis具有更好的性能和更完整的功能支持。如果不想使用Lettuce,可以使用以下配置:
spring:
redis:
host: localhost # Redis服务器地址
port: 6379 # Redis服务器端口号
password: # Redis服务器密码,如果没有密码可以不填
database: 0 # Redis数据库编号,从0到15,默认为0
jedis:
pool:
max-active: 8 # 连接池最大连接数,默认为8
max-idle: 8 # 连接池中最大的空闲连接数,默认为8
min-idle: 0 # 连接池中最小的空闲连接数,默认为0
max-wait: -1ms # 连接池最大等待时间,-1表示无限等待,默认为-1ms
以上配置中的jedis是指使用Jedis作为Redis客户端的实现,Jedis是Redis官方推荐的Java客户端,它与Lettuce相比在性能和功能上略有欠缺。
三、分布式锁代码
1、自己实现
@Service
public class RedisLockService {
@Autowired
private RedisTemplate redisTemplate;
private static final String LOCK_PREFIX = "lock:";
public boolean lock(String key, long expireTime) {
String lockKey = LOCK_PREFIX + key;
long currentTime = System.currentTimeMillis();
long lockExpireTime = currentTime + expireTime;
Boolean result = redisTemplate.opsForValue().setIfAbsent(lockKey, lockExpireTime);
if (result != null && result) {
// 设置锁过期时间
redisTemplate.expire(lockKey, expireTime, TimeUnit.MILLISECONDS);
return true;
}
// 判断锁是否过期
Object lockValue = redisTemplate.opsForValue().get(lockKey);
if (lockValue != null && Long.parseLong(lockValue.toString()) < currentTime) {
// 获取锁的当前过期时间
Long oldExpireTime = Long.parseLong(redisTemplate.opsForValue().getAndSet(lockKey, lockExpireTime).toString());
if (oldExpireTime != null && oldExpireTime.equals(lockValue)) {
// 设置锁过期时间
redisTemplate.expire(lockKey, expireTime, TimeUnit.MILLISECONDS);
return true;
}
}
return false;
}
public void unlock(String key) {
redisTemplate.delete(LOCK_PREFIX + key);
}
}
上面的代码并发下不是原子操作,因为在执行getAndSet和expire方法之间可能会存在一段时间窗口,在这个时间窗口内,其他线程可能会获取到锁,从而导致出现锁竞争的情况
除了上述提到的写法之外,还可以通过使用Lua脚本的方式来优化分布式锁的实现。Lua脚本可以在Redis中原子执行一系列命令,从而避免在分布式环境下发生竞争的问题。
下面是一种基于Lua脚本的分布式锁实现方式
public boolean lock(String lockKey, String lockValue, long expireTime) {
// 使用Lua脚本执行加锁操作
String script = "if redis.call('setnx', KEYS[1], ARGV[1]) == 1 then " +
"redis.call('pexpire', KEYS[1], ARGV[2]); return true; " +
"else return false; end;";
RedisScript<Boolean> redisScript = RedisScript.of(script, Boolean.class);
Boolean result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), lockValue, expireTime);
return result != null && result;
}
public boolean unlock(String lockKey, String lockValue) {
// 使用Lua脚本执行释放锁操作
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then " +
"return redis.call('del', KEYS[1]); else return 0; end;";
RedisScript<Long> redisScript = RedisScript.of(script, Long.class);
Long result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), lockValue);
return result != null && result > 0;
}
private static final String LUA_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then" +
" redis.call('set', KEYS[1], ARGV[2])" +
" redis.call('expire', KEYS[1], ARGV[3])" +
" return 'true'" +
"else" +
" return 'false'" +
"end";
public boolean tryLock(String key, String value, long expireTime) {
String lockKey = LOCK_PREFIX + key;
long currentTime = System.currentTimeMillis();
String lockExpireTime = String.valueOf(currentTime + expireTime);
String result = redisTemplate.execute(new RedisScript<String>() {
@Override
public String getSha1() {
return DigestUtils.sha1DigestAsHex(LUA_SCRIPT);
}
@Override
public Class<String> getResultType() {
return String.class;
}
@Override
public String getScriptAsString() {
return LUA_SCRIPT;
}
}, Collections.singletonList(lockKey), value, lockExpireTime, String.valueOf(expireTime));
return "true".equals(result);
}
如果想要保证原子性,我们可以使用Redis事务(Transaction)来实现。Redis事务可以将多个Redis操作打包成一个原子性的操作,要么全部执行,要么全部不执行。因此,在锁的获取和释放过程中,我们可以将多个Redis操作打包成一个事务,这样就可以保证原子性。例如:
public boolean lock(String key, long expireTime) {
String lockKey = LOCK_PREFIX + key;
long lockExpireTime = System.currentTimeMillis() + expireTime;
while (true) {
// 监视锁的key,事务开始
redisTemplate.watch(lockKey);
Object lockValue = redisTemplate.opsForValue().get(lockKey);
if (lockValue == null || Long.parseLong(lockValue.toString()) < System.currentTimeMillis()) {
// 开启事务
redisTemplate.multi();
redisTemplate.opsForValue().set(lockKey, lockExpireTime);
redisTemplate.expire(lockKey, expireTime, TimeUnit.MILLISECONDS);
List<Object> results = redisTemplate.exec();
// 如果事务执行成功,说明获取锁成功
if (results != null) {
return true;
}
}
// 取消监视
redisTemplate.unwatch();
try {
// 等待一段时间后重试获取锁
Thread.sleep(100L);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
}
在这个实现中,我们使用了Redis事务来实现多个操作的原子性。在获取锁的过程中,如果锁不存在或锁已经过期,我们就使用multi()开启一个事务,并将set()和expire()操作打包在事务中,然后使用exec()执行事务。如果事务执行成功,说明获取锁成功;如果事务执行失败,说明有其他线程在此期间修改了锁的值,获取锁失败。为了避免多个线程同时修改锁的值,我们使用watch()监视锁的key,在事务开始前,先将锁的key监视起来,这样在事务执行期间,如果有其他线程修改了锁的值,就会取消当前事务的执行,从而避免了并发问题。
2、工具
使用 Redisson 分布式锁实现,该库已经封装好了 Redis 分布式锁的相关细节
在 pom.xml
中添加 Redisson 依赖:
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.16.1</version>
</dependency>
Spring Boot 的配置文件中添加 Redisson 的配置:
spring:
redis:
host: localhost
port: 6379
password:
database: 0
redisson:
config: classpath:redisson.yaml # 配置文件路径
resources
目录下创建 redisson.yaml
配置文件:
singleServerConfig:
address: "redis://${spring.redis.host}:${spring.redis.port}"
password: ${spring.redis.password}
database: ${spring.redis.database}
connectTimeout: 30000
timeout: 10000
pingTimeout: 1000
idleConnectionTimeout: 60000
retryAttempts: 3
retryInterval: 1500
connectionMinimumIdleSize: 2
connectionPoolSize: 16
- 编写 Redis 分布式锁的工具类
RedisLockUtils
:
@Component
public class RedisLockUtils {
@Autowired
private RedissonClient redissonClient;
/**
* 获取分布式锁
*
* @param lockKey 锁的键
* @param expireTime 锁的过期时间
* @param waitTimeout 等待获取锁的超时时间
* @return 是否成功获取锁
*/
public boolean lock(String lockKey, long expireTime, long waitTimeout) {
RLock lock = redissonClient.getLock(lockKey);
try {
return lock.tryLock(waitTimeout, expireTime, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
return false;
}
}
/**
* 释放分布式锁
*
* @param lockKey 锁的键
*/
public void unlock(String lockKey) {
RLock lock = redissonClient.getLock(lockKey);
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
- 在需要加锁的业务代码中使用
RedisLockUtils
工具类获取分布式锁:
@Autowired
private RedisLockUtils redisLockUtils;
public void doSomething() {
String lockKey = "myLock";
long expireTime = 5000L; // 5 秒钟
long waitTimeout = 1000L; // 1 秒钟
boolean locked = redisLockUtils.lock(lockKey, expireTime, waitTimeout);
if (locked) {
try {
// TODO: 执行需要加锁的业务代码
} finally {
redisLockUtils.unlock(lockKey);
}
} else {
// TODO: 获取锁失败,处理业务逻辑
}
}
使用 Redisson 分布式锁可以省去很多手写 Redis 分布式锁时需要注意的细节,让我们的代码更加简洁和易于维护。当然,还有其他的一些库也提供了分布式锁的实现,例如 Curator、Zookeeper 等