Redisson实现分布式锁案例
- 引入依赖
xml
复制代码
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.23.2</version>
</dependency>
- 创建Redisson配置类
java
复制代码
@Configuration
public class RedissonConfig {
@Bean
public RedissonClient redissonClient() {
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379");
// 如果有密码需要设置密码
return Redisson.create(config);
}
}
- 使用分布式锁
java
复制代码
@RestController
public class LockController {
@Resource
private RedissonClient redissonClient;
@RequestMapping("/lock")
public String lockResource() throws InterruptedException {
String lockKey = "myLock";
// 获取锁
RLock lock = redissonClient.getLock(lockKey);
try {
// 超时时间 20s, [tryLock 获取成功才需要释放锁,获取失败不需要释放锁]
boolean isLocked = lock.tryLock(20, TimeUnit.SECONDS);
if(isLocked) {
// 成功获取到锁
try {
TimeUnit.SECONDS.sleep(5);
return "成功获取到锁,并执行业务代码";
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 释放锁
lock.unlock();
}
} else {
// 获取锁失败
return "获取锁失败";
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return "获取锁成功";
}
}```