引入包
代码语言:javascript复制 <dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.10.0</version>
</dependency>
RedissonConfig类:
代码语言:javascript复制package com.xiepanpan.locks.lockstest.config;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author: xiepanpan
* @Date: 2020/2/24
* @Description: redisson 配置类
*/
@Configuration
public class RedissonConfig {
@Bean
RedissonClient redisson() {
Config config = new Config();
config.useSingleServer().setAddress("redis://192.168.217.130:6379");
return Redisson.create(config);
}
}
代码语言:javascript复制 @Autowired
RedissonClient redissonClient;
public void useRedissonForLock() {
//1、获取一把锁。只要各个代码,用的锁名一样即可
RLock lock = redissonClient.getLock("lock");
try {
// 一直等待 阻塞住
// lock.lock();
//加锁带自动解锁 三秒后自动解锁
lock.lock(3,TimeUnit.SECONDS);
Jedis jedis = jedisPool.getResource();
String num = jedis.get("num");
Integer i = Integer.parseInt(num);
i =1;
jedis.set("num",i.toString());
jedis.close();
} finally {
lock.unlock();
}
}
redisson有个看门狗功能 lockWatchdogTimeout(监控锁的看门狗超时,单位:毫秒) 默认情况下,加锁的时间是30秒.如果加锁的业务没有执行完,那么有效期到 30-10 = 20秒的时候,就会进行一次续期,把锁重置成30秒.
redisson官方文档: https://github.com/redisson/redisson/wiki/目录
参考博客: https://blog.csdn.net/zl1zl2zl3/article/details/90544747 https://www.cnblogs.com/kiko2014551511/p/11527108.html