1、引入jar包
<dependency> <groupId>org.redisson</groupId> <artifactId>redisson</artifactId> <version>3.13.4</version> </dependency>
2、增加Configuration类
@Configuration public class RedissonConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private String port; @Value("${spring.redis.password}") private String password; @Bean public RedissonClient getRedisson() { Config config = new Config(); config.useSingleServer().setAddress("redis://" + host + ":" + port).setPassword(password); return Redisson.create(config); } }
3、使用redission分布式锁
@Autowired
private RedissonClient redissonClient; //方法区 String key = "aa:bb:cc:01"; RLock rLock =redissonClient.getLock(key); try{
// 尝试加锁,最多等待1秒,上锁以后10秒自动解锁
// 没有Watch Dog ,10s后自动释放 boolean res = rLock.tryLock(1,10, TimeUnit.SECONDS); if(!res){ return new GeneralVO<>(400, "请勿重复提交", false); } }finally{ rLock.unlock(); }
private void redissonDoc() throws InterruptedException { //1. 普通的可重入锁 RLock lock = redissonClient.getLock("generalLock"); // 拿锁失败时会不停的重试 // 具有Watch Dog 自动延期机制 默认续30s 每隔30/3=10 秒续到30s lock.lock(); // 尝试拿锁10s后停止重试,返回false // 具有Watch Dog 自动延期机制 默认续30s boolean res1 = lock.tryLock(10, TimeUnit.SECONDS); // 拿锁失败时会不停的重试 // 没有Watch Dog ,10s后自动释放 lock.lock(10, TimeUnit.SECONDS); // 尝试拿锁100s后停止重试,返回false // 没有Watch Dog ,10s后自动释放 boolean res2 = lock.tryLock(100, 10, TimeUnit.SECONDS); //2. 公平锁 保证 Redisson 客户端线程将以其请求的顺序获得锁 RLock fairLock = redissonClient.getFairLock("fairLock"); //3. 读写锁 没错与JDK中ReentrantLock的读写锁效果一样 RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("readWriteLock"); readWriteLock.readLock().lock(); readWriteLock.writeLock().lock(); }