文章目录
前言
Redisson简介
省略…
Redisson的优势
提供了看门狗
Redisson
提供了一个监控锁的看门狗(watch dog
),它的作用是在Redisson
实例被关闭前,不断(默认每10s)的延长锁(redis
中的目标key)的有效期(默认续期到30s),也就是说,如果一个拿到锁的线程一直没有完成逻辑,那么看门狗会帮助线程不断的延长锁的超时时间,锁不会因为超时而被释放。加锁的业务只要运行完成,就不会给当前锁续期,即使不手动解锁,锁默认会在30s内自动过期,不会产生死锁问题;
默认情况下,看门狗的续期时间是30s,也可以通过修改Config.lockWatchdogTimeout
来另行指定。
另外Redisson
还提供了可以指定leaseTime
参数的加锁方法来指定加锁的时间。超过这个时间后锁便自动解开了,不会延长锁的有效期。
提供了多种锁
redisson 还有公平锁、读写锁的实现。
public interface RedissonClient {
/**
* 获取锁(默认的非公平锁)
*/
RLock getLock(String name);
/**
* 获取公平锁
*/
RLock getFairLock(String name);
/**
* 获取读写锁
*/
RReadWriteLock getReadWriteLock(String name);
}
public interface RLock extends Lock, RExpirable, RLockAsync {
void lockInterruptibly(long leaseTime, TimeUnit unit) throws InterruptedException;
boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException;
void lock(long leaseTime, TimeUnit unit);
boolean forceUnlock();
boolean isLocked();
boolean isHeldByCurrentThread();
int getHoldCount();
}
实战
加依赖
<!--redisson-->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.13.6</version>
<exclusions>
<exclusion>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-data-23</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-data-21</artifactId>
<version>3.13.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot