一、概念与简介
Redisson是架设在Redis基础上的一个Java驻内存数据网格,Redis官方推荐的Java分布式锁的解决方案
二、依赖与配置类
<dependency><groupId>org.redisson</groupId><artifactId>redisson</artifactId><version>3.15.6</version></dependency>
@Configuration
public class MyRedissonConfig {
@Bean(destroyMethod="shutdown")
RedissonClient redisson() throws IOException{
Config config = new Config();
// 存在密码的话,一定要设置密码
config.useSingleServer()
.setAddress("redis://127.0.0.1:6379")
.setPassword("123456");
//设置看门狗的时间,不配置的话默认30000
config.setLockWatchdogTimeout(30000);
return Redisson.create(config);
}
}
三、实现与测试
实现WatchDog机制
@Autowired
RedissonClient redissonClient;
@GetMapping("/redisson/test1")
public String hello(){
long threadId = Thread.currentThread().getId();
long businessHours = 50000;
log.info("线程{}进入代码中,{}",threadId, LocalDateTime.now());
// 只要名字一样就是同一把锁
RLock lock = redissonClient.getLock("lock");
// 加锁,如果没锁上就一会只等待知道加锁成功
lock.lock(); // 默认30秒过期时间,开启watchdog机制
// lock.lock(5,TimeUnit.SECONDS); // 加了过期时间后,就不会开启watchdog机制
log.info("线程{}获取到锁,开始执行业务,此刻时间{},总共工作时间{}",threadId, LocalDateTime.now(),businessHours/1000);
try{
Thread.sleep(businessHours);
log.info("线程{}完成业务,{}",threadId, LocalDateTime.now());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 一定一定不能忘记在finally里面解锁!!!
log.info("线程{}准备释放锁,{}",threadId, LocalDateTime.now());
lock.unlock();
log.info("线程{}释放锁成功,{}",threadId, LocalDateTime.now());
}
return "hello";
}
@GetMapping("/redisson/test2")
public String hello2(){
long threadId = Thread.currentThread().getId();
long businessHours = 40000;
log.info("线程{}进入代码中,{}",threadId, LocalDateTime.now());
// 只要名字一样就是同一把锁
RLock lock = redissonClient.getLock("lock");
// 加锁,如果没锁上就一会只等待知道加锁成功
// lock.lock(); // 默认30秒过期时间,开启watchdog机制
lock.lock(10, TimeUnit.SECONDS); // 加了过期时间后,就不会开启watchdog机制
log.info("线程{}获取到锁,开始执行业务,此刻时间{},总共工作时间{}",threadId, LocalDateTime.now(),businessHours/1000);
try{
Thread.sleep(businessHours);
log.info("线程{}完成业务,{}",threadId, LocalDateTime.now());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (lock.isLocked() && lock.isHeldByCurrentThread()) {
log.info("线程{}准备释放锁,{}",threadId, LocalDateTime.now());
lock.unlock();
log.info("线程{}释放锁成功,{}",threadId, LocalDateTime.now());
}
}
return "hello";
}
@GetMapping("/redisson/testTryLock")
public String testTryLock() throws InterruptedException {
RLock watchDogLock = redissonClient.getLock("watchDogLock");
//进行3s的尝试时间,如果失败则返回false, 还可以设置锁过期时间(第二个参数),如果设置会导致看门狗无效
boolean judge = watchDogLock.tryLock(3, TimeUnit.SECONDS);
//输出是否能够获取到锁
System.out.println(Thread.currentThread().getName() + "的锁获取情况:" + judge);
//如果获取到锁
if (judge){
try {
System.out.println(Thread.currentThread().getName() + " 已经成功获取到的分布式锁" + System.currentTimeMillis());
//执行主要业务逻辑
Thread.sleep(40000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//最后进行解锁操作,如果服务宕机,则到不了这一步,会等待看门狗监控锁结束锁清除
System.out.println(Thread.currentThread().getName() + " 进行解锁操作" + System.currentTimeMillis());
watchDogLock.unlock();
}
return "成功获取到分布式锁";
}else {
//如果没有获取到分布式锁,执行业务逻辑
System.out.println(Thread.currentThread().getName() + " 没有成功获取到分布式锁,锁已经被占用" + System.currentTimeMillis());
return "没有获取到分布式锁";
}
}
重要的话说三遍:一定不要忘记在finally代码块里unlock!!!
Redisson实现接口限流效果
RRateLimiter rateLimiter;
@PostConstruct
public void initRateLimiter(){
RRateLimiter ra = redissonClient.getRateLimiter("rate-limiter");
// 1分钟只允许6个请求
// setRate 我们项目服务重启,就会强制重置之前的限流配置与状态,以当前为准
ra.setRate(RateType.OVERALL, 6, 1, RateIntervalUnit.MINUTES);
rateLimiter = ra;
}
---------
@GetMapping("/rate/limiter")
public String testRateLimiter() {
boolean b = rateLimiter.tryAcquire(1);
if (!b) {
return "fail";
}
// 执行业务
return "ok";
}
Zset类型中Sore中保存的是时间戳 Q:连续请求了两次,两分钟后再请求?请问可以请求多少次? A:如果两个请求时间间隔大于规定时间窗,那么,这个请求就会重置令牌桶数量
四、问题
使用lock.lock(10, TimeUnit.SECONDS)后
如果,业务时间大于过期时间,那么,只要锁过期,那个其它请求就可以进来执行业务!(超时同时操作请求>=2),最后unlock时会报错,因为锁已经过期了!
使用lock.lock()会执行watchdog机制
如果,业务时间大于过期时间,它也会帮你续上过期时间!但如果线程出现问题,最后没有执行unlock,这个锁也会被一直续时间,无法释放(除非redis或项目停止)!其它请求也无法获取到锁!
为什么说它是可重入性锁?
一个线程可以的多个流程可以同时拿到这个锁;只有这样才能进行时间的续期;
多久加一次过期时间?
每当过期时间减少了1/3 ,redis过期时间就会重新恢复到设置值(setLockWatchdogTimeout)
使用lock(),其它线程会怎样?
会一直阻塞在redissson的等待队列中,该线程资源也会一直被持有,直到获取到锁或停机
实现分布式锁为什么推荐lock()?
tryLock一般用于特定满足需求的场合,但不建议作为一般需求的分布式锁,一般分布式锁建议用void lock(long leaseTime, TimeUnit unit)。因为从性能上考虑,在高并发情况下后者效率是前者的好几倍
使用tryLock()有什么作用?
使用tryLock()其它线程没有获取到锁时,我们可以让它直接退出,而不必一直阻塞不释放线程资源!
watchdog执行流程

资料学习与引用:
