1.引入redisson
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.15.6</version>
</dependency>
2.注入redissonClient
@Configuration
public class RedissonConfig {
@Value("${spring.redisson.address}")
private String redissonAddress;
@Value("${spring.redisson.db}")
private Integer redissonDB;
@Bean
public RedissonClient redissonClient() {
Config config = new Config();
config.useSingleServer()
.setAddress(redissonAddress)
.setDatabase(redissonDB);
return Redisson.create(config);
}
}
3.使用锁
private final RedissonClient redissonClient;
String redissonKey = "";
RLock rLock = redissonClient.getLock(redissonKey);
rLock.lock(paramConfig.getRedissonUserWaitTimeout(), TimeUnit.SECONDS);
try {
...
} catch (Exception e) {
log.error("Error,", e);
} finally {
log.info("unlock, redissonKey:{}", redissonKey);
if (rLock.isLocked()) {
rLock.unlock();
}
}