1.背景
最近接到一个需求,需要确保同一时间只有一个用户进行特定操作,等待该用户操作结束后,其他用户才可以继续进行,想到可以使用锁机制实现,为当前正在执行操作的用户加锁,等待操作结束后释放锁,以实现同一时间只有一个用户能够进行相应的操作。
最后决定使用 StringRedisTemplate 在 Spring Boot 中实现一个简单的 Redis 分布式锁。
2.代码实现
(1)项目使用的是Springboot框架进行开发,首先导入相应的redis依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
(2)Redis锁工具类
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
@Component
public class RedisLockUtil {
@Resource
private StringRedisTemplate stringredisTemplate;
private static final String LOCK_KEY_PREFIX = "lock:";
public boolean tryLock(String lockKey, long timeout, TimeUnit unit) {
Boolean success = stringredisTemplate.opsForValue().setIfAbsent(LOCK_KEY_PREFIX + lockKey, "locked", timeout, unit);
return success != null && success;
}
public void unlock(String lockKey) {
stringredisTemplate.delete(LOCK_KEY_PREFIX + lockKey);
}
}
代码解析:
- 依赖注入:
使用 @Resource 注入 StringRedisTemplate,这个类提供了对 Redis 字符串的操作方法。
注:在使用@Resource进行依赖注入时,要确保你的StringRedisTemplate Bean的名称与 @Resource中的名称一致,即如果你使用 @Resource 注解的字段名是stringRedisTemplate,那么 Spring 会寻找一个名为 stringRedisTemplate 的Bean,如果Bean的名称与字段名不匹配,就会导致注入失败,这是因为 @Resource 默认按名称(byName)注入,期望找到一个与指定名称匹配的 Bean,如果想要Bean名称不一样的话,可以改用 @Autowired 注解,它默认按类型注入,不需要关心Bean的名称。
@Autowired和@Resource的具体用法可参照这篇文章:@Autowired和@Resource的区别
- 锁的获取 (tryLock 方法):
使用 setIfAbsent 方法尝试设置一个键(lock:lockKey),如果该键不存在,则设置成功并返回 true。设置的值是一个简单的字符串 “locked”,并且我们可以指定一个过期时间,避免死锁情况。
- 锁的释放 (unlock 方法):
使用 delete 方法删除锁键,释放锁。
3.使用示例
@Autowired
private RedisLockUtil redisLockUtil;
public CommonResult<> () {
String lockKey = "example";
boolean lockAcquired = redisLockUtil.tryLock(lockKey, 3, TimeUnit.MINUTES); // 锁超时时间3分钟
if (!lockAcquired) {
return CommonResult.error("系统正在处理,请稍后再试");
}
try {
// 执行你的业务代码
} finally {
redisLockUtil.unlock(lockKey); // 释放锁
}
}
4. 注意事项
锁的粒度:锁的粒度应该根据业务需求合理设计,避免不必要的资源竞争。
锁超时:确保设置合理的锁超时时间,防止长时间占用锁导致系统性能下降。
锁释放:确保在业务逻辑完成后一定释放锁,建议使用 finally 块来保证。