1. 前言
分布式锁可以保证在分布式系统集群部署的时候,同一个方法在同一时间只能被集群中的一台机器的一个线程执行。
Redisson是一个基于java的客户端,提供了很多功能。其中就包括分布式锁的实现,参考官当文档在加锁后可能会存在,业务逻辑还未处理完而锁已经到期释放的场景。因此,Redisson引入了Watch Dog(看门狗)的机制,它会定期监测业务是否处理完毕,如果业务还未执行完毕锁又快要到期了,他会自动帮我们把锁进行续期。
这里值得注意的是,要想触发看门狗机制,我们在加锁的时候不能设置leaseTime或者设置为-1。Redisson默认加锁时间30s,每隔10s会刷新加锁时间。
2.引入依赖
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>${redisson.version}</version>
</dependency>
3.创建Redisson客户端
@Configuration
public class RedissonConfiguration {
@Bean(destroyMethod = "shutdown")
public RedissonClient redisson() {
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379");
return Redisson.create(config);
}
}
4.使用分布式锁
@Service
public class OrderService {
@Resource
private RedissonClient redisson;
public void testLock() {
// 获取分布式锁
RLock lock = redisson.getLock("myLock");
try {
// 尝试加锁,最多等待10秒,锁的持有时间默认为30秒
//此处没有设置leaseTime,会自动启动看门狗机制
boolean isLocked = lock.tryLock(10, TimeUnit.SECONDS);
if (isLocked) {
// 成功获取到锁
log.debug("线程:" + Thread.currentThread().getName() + "获得了锁");
// 执行需要加锁的代码逻辑
// ...
} else {
log.debug("获取锁失败");
// 获取锁失败
// 处理获取锁失败的逻辑
// ...
}
} catch (InterruptedException e) {
// 处理中断异常
log.error(e.getMessage(), e);
} finally {
// 释放锁
if(lock.isLocked() && lock.isHeldByCurrentThread()){
lock.unlock();
log.debug("释放锁成功");
}
}
}
}
至此,一个简单的分布式锁就实现了。