maven依赖
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.9.1</version>
</dependency>注入实例 yml文件 配置host 密码 spring.redis.host 等
@Configuration
public class RedissonConfig {
@Autowired
private RedisProperties properties;
@Bean
public RedissonClient redisson() {
Config config = new Config();
// 单机模式
config.useSingleServer()
.setAddress("redis://"+properties.getHost()+":" +properties.getPort())
.setDatabase(properties.getDatabase())
.setPassword(properties.getPassword());
return Redisson.create(config);
}
}业务代码
RLock lock = redissonClient.getLock("testLock");
try {
//尝试加锁,最多等待3秒,上锁以后5秒自动解锁
boolean res = lock.tryLock(3, 5, TimeUnit.SECONDS);
if (res) {
// 业务代
}
} catch (InterruptedException e) {
log.error("分布式锁{}获取失败", lock.getName());
throw new BusinessProcessFailException("分布式锁【" + lock.getName() + "】获取失败", ErrorCode.SYSTEM_EXCEPTION.getCode());
} finally {
//判断要解锁的key是否被当前线程持有。
if (lock.isLocked() && lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
版权声明:本文为qq_41029282原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。