个人博客传送门
- 基于redisson的分布式缓存和springboot的整合实现
- 对于锁的选择:可重入锁、可重入公平锁、联锁、红锁等
- 对于业务场景的支持:
- lock.lock() 不设置过期时间和等待时间
- lock.lock(10,TimeUnit) 设置过期时间,超过过期时间主动释放锁
- lock.lock(20,10,TimeUnit) 设置竞争获取锁的最大等待时间和锁的超时时间
<dependency><groupId&disson</groupId><artifactId>redisson-spring-boot-starter</artifactId><version>${version}</version>
</dependency>
- 版本需要注意和springboot的版本需要兼容具体的根据springboot的版本进行选择
- 对于关系可以参考 redisson整合springboot
spring:redis:database: #库名host: #主机名port: #端口号password: #密码ssl: #ssl认证timeout: #超时时间 cluster: nodes: #集群的节点sentinel:master: #哨兵的masternamenodes: #节点
参数的具体说明和配置可以参考文档 配置方法
可以注入RedissonClient或者RedisTemplate使用
@ResourceRedissonClient redissonClient;/*** rule** @return* @throws InterruptedException*/@GetMapping("/lock")public String lock() throws InterruptedException {RLock lock = FairLock("anyLock");// 尝试加锁,最多等待10秒,上锁以后10秒自动解锁Lock( 10,10, TimeUnit.SECONDS);try {log.info("lock 睡眠开始");//具体的业务操作Thread.sleep(9000);log.info("lock 睡眠结束");} catch (InterruptedException e) {e.printStackTrace();} finally {log.info("lock 主动释放锁");lock.unlock();}return "";}
@GetMapping("/tryLock")public String tryLock() throws InterruptedException {RLock lock = FairLock("anyLock");if(lock.isLocked()){// 尝试加锁,最多等待20秒,上锁以后10秒自动解锁boolean res = Lock(20, 10, TimeUnit.SECONDS);log.info("tryLock 方法获取到锁:{}",res);if (res) {try {log.info("tryLock 睡眠开始");Thread.sleep(9000);log.info("tryLock 睡眠结束");} catch (InterruptedException e) {e.printStackTrace();} finally {lock.unlock();log.info("tryLock 主动释放锁");}}else {log.info("tryLock 方法未获取到锁:{}",res);}}else {//查询接口,未加锁直接获取当前的redis数据log.info("未加锁直接过去资源");}return "";}
@Slf4j
@Component
public class RedissonLockUtil {@ResourceRedissonClient redissonClient;/*** 主动获取锁,若超时直接返回异常* * @param lockName 锁定资源的key * @param waitTime 获取锁最大等待时间* @param timeOutTime 超时时间* @return* @throws InterruptedException*/public boolean tryLock(String lockName,long waitTime,long timeOutTime) throws InterruptedException {RLock fairLock = FairLock(lockName);Lock( waitTime,timeOutTime, TimeUnit.SECONDS);}/*** 查询时候判断是否可以进行查询操作,若超时直接返回异常** @param lockName 锁定资源的key * @param waitTime 获取锁最大等待时间* @param timeOutTime 超时时间* @return* @throws InterruptedException*/public boolean queryAndTryLock(String lockName, long waitTime, long timeOutTime) throws InterruptedException {RLock lock = FairLock(lockName);if(lock.isLocked()){Lock(waitTime, timeOutTime, TimeUnit.SECONDS);}else {log.info("未加锁直接获取资源");return true;}}
本文发布于:2024-02-04 20:36:33,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170715903259393.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |