Redisson分布式锁
在集群服务中使用redis,一般需要使用redisson 分布式锁。
1. 引入jar
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.17.4</version>
</dependency>
2.test 测试类
boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException;
第一个参数(等待时间),如果设置了,获取锁失败后,就不会立即返回了;会在等待内不断重试;如果在等待时间结束后,还没有获取到锁,那就失败了。所以设置后就变成了可重试的锁了。 第二个参数(锁失效后自动释放的时间,不填默认为-1, -1 表示自动续锁) 第三个参数(时间单位)
RLock lock = redissonClient.getLock("myLock");
boolean isLocked = false;
try {
// 尝试获取锁,最多等待10秒,获取后锁持有时间为30秒
isLocked = lock.tryLock(10, 30, TimeUnit.SECONDS);
if (isLocked) {
try {
// 获取到锁后执行的代码
System.out.println("Lock acquired, performing safe operations...");
// 这里可以放置需要同步的代码块
} finally {
// 释放锁
lock.unlock();
System.out.println("Lock released");
}
} else {
// 无法获取锁,执行其他操作
System.out.println("Unable to acquire lock within the specified wait time");
}
} catch (InterruptedException e) {
// 处理中断异常
Thread.currentThread().interrupt(); // 恢复中断状态
System.err.println("Lock acquisition interrupted");
} finally {
// 注意:通常不需要在这里关闭Redisson客户端,因为它是共享资源
// 除非你确定这个RedissonClient实例不再被需要,并且你想释放它占用的资源
// redissonClient.shutdown(); // 不推荐在每次使用完锁后立即关闭客户端
}

浙公网安备 33010602011771号