当前位置:网站首页>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();
}
}
}
}
边栏推荐
- 基于 LSTM 的分布式能源发电预测(Matlab代码实现)
- E - Sugoroku 3(期望dp)
- 【云原生】Kubernetes编排工具精讲
- NTP SERVICE TASK 在GWserver配置、启用NTP服务,为当前环境提供时钟同步服务,Client主机可以从该服务器同步时间。
- NTU General Database-Gbase-8a-Learning-04-Deploying Distributed Clusters
- The technical aspects of the byte have been passed, and the salary has been negotiated for 20K*13, but the result is still being brushed. I asked the HR why...
- 漫谈缺陷管理的自动化实践方案
- When knowledge and action are one
- 分布式数据库难题(三):数据一致性
- Leetcode81. 搜索旋转排序数组 II
猜你喜欢
随机推荐
Eureka自我保护
无源晶振负载电容值CL匹配方法及说明
Golden Warehouse Database KingbaseGIS User Manual (6.6. Geometric Object Verification Function, 6.7. Spatial Reference System Function)
数字孪生电力系统,可视化应用实现科学调度的电子设备
断开和服务器共享连接的方法「建议收藏」
[Cloud native] Kubernetes orchestration tools
[C language] Address book "Static Memory Version"
Wireshark classic practice and interview 13-point summary
CST Studio Suite 2021 software installation package and installation tutorial
ES6 从入门到精通 # 15:生成器 Generator 的用法
JVM内存和垃圾回收-10.直接内存
生成树和交换的总结
信息系统项目管理师核心考点(六十四)信息安全基础知识重要概念
The older tester has just passed the "hurdle" of being 35 years old, and I want to tell you something from my heart
使用C语言实现静态链表
ETCD快速入门-02 ETCD安装
【SSL集训DAY2】有趣的数【数位DP】
vmware Exsi 网卡配置
Eureka protects itself
博弈小游戏