SpringBoot often uses redis distributed locks during work, such as changing the amount. Spring integration redis provides a solution. The following are the steps to use.
maven importspring-integration-redis
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-redis</artifactId>
<version>5.3.1.RELEASE</version>
</dependency>
Define RedisLockRegistry
Beans
@Bean(destroyMethod = "destroy")
public RedisLockRegistry redisLockRegistry(RedisConnectionFactory redisConnectionFactory) {
return new RedisLockRegistry(redisConnectionFactory, “app_name_lock_registry”);
}
used in business code,
@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();
}