工作中SpringBoot经常要用到redis分布式锁,比如更改金额,spring integration redis提供了解决方案,以下是使用步骤。
maven引入spring-integration-redis
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-redis</artifactId>
<version>5.3.1.RELEASE</version>
</dependency>
定义RedisLockRegistry
Bean
@Bean(destroyMethod = "destroy")
public RedisLockRegistry redisLockRegistry(RedisConnectionFactory redisConnectionFactory) {
return new RedisLockRegistry(redisConnectionFactory, “app_name_lock_registry”);
}
业务代码中使用,
@Autowired
private RedisLockRegistry redisLockRegistry;
Lock lock = redisLockRegistry.obtain("lock_prefix" + id);
try {
boolean got = lock .tryLock(1L, SECONDS);
if(!got){
throw new RuntimeException(msg);
}
} catch (InterruptedException e) {
throw new RuntimeException(msg);
}
try{
//业务逻辑
}catch(Exception e){
}finally{
lock.unlock();
}