当前位置:网站首页>Redisson 分布式锁
Redisson 分布式锁
2022-08-09 23:33:00 【川流不息的车呀】
@Service
@Slf4j
public class RedissonUtils {
@Autowired
private RedissonClient redissonClient;
public RLock lock(String s, int seconds) {
RLock rlock = redissonClient.getLock(s);
rlock.lock(seconds, TimeUnit.SECONDS);
return rlock;
}
}
Redis 版本比较高的,连接redis地址要加redis://,否则连接会报错
@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class RedissonConfiguration {
@Autowired
private RedisProperties redisProperties;
@Bean
public RedissonClient redissonClient() {
Config config = new Config();
String redissonAddr = "redis://" + redisProperties.getHost() + ":" + redisProperties.getPort();
config.useSingleServer().setAddress(redissonAddr);
config.useSingleServer().setDatabase(redisProperties.getDatabase());
return Redisson.create(config);
}
}
配置文件获取redis配置参数:
@Component
@ConfigurationProperties(prefix = "spring.redis")
@Data
public class RedisProperties {
private String host;
private Integer port;
private Integer database;
}
具体使用如下:
首先unlock最好写在finally里面,不管异常情况,最终都会执行,防止异常情况下,锁没有及时删除的情况(虽然设置过期时间,如果过期时间比较长,下次调用会获取不到锁)
if (locked.isLocked() && locked.isHeldByCurrentThread())
锁过期时间短,已经删除的情况下使用。否则报错:java.lang.IllegalMonitorStateException: attempt to unlock lock, not locked by current thread by node
@Override
public void setUpShop(setUpRequest request){
RLock locked = null;
try {
String key = "设置的key";
locked = redissonUtils.lock(key, 1);
if (locked != null) {
//处理业务
}
} finally {
if (locked != null) {
//判断要解锁的key是否已被锁定;判断要解锁的key是否被当前线程持有
if (locked.isLocked() && locked.isHeldByCurrentThread()) {
locked.unlock();
}
}
}
}
边栏推荐
猜你喜欢
随机推荐
基于ABP的AppUser对象扩展
新开窗口 展示协议
LSTM-based distributed energy generation prediction (Matlab code implementation)
C语言学习之旅 【操作符(残缺版)】
分布式数据库难题(二):数据复制
数据库的备份与恢复「建议收藏」
Alibaba Cloud SMS Service Activation
信息系统项目管理师核心考点(六十四)信息安全基础知识重要概念
Project (7) - PolarSeg point cloud semantic segmentation
Dry goods!Towards robust test-time adaptation
go语言的并发原理(goroutine)
重估HR SaaS:一体化后的新三年
Leecode-205. 同构字符串
Leetcode83. 删除排序链表中的重复元素
Why don't suggest you run in Docker Mysql?
【C语言】通讯录《静态内存版本》
New window Display Agreement
阿雷的血压有些低
In-depth understanding of multithreading (Part 1)
数字孪生智慧制造生产线项目实施方案,平台认知与概念