redission 分布式锁
pom.xml
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.6.5</version>
</dependency>
RedissonConfig
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.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);
//添加主从配置
// config.useMasterSlaveServers().setMasterAddress("").setPassword("").addSlaveAddress(new String[]{"",""});
return Redisson.create(config);
}
}
serviceImpl 片段
import org.redisson.api.RedissonClient;
...
//加锁
String lockTitle = "placeLock_";
RLock rlock = redissonClient.getLock(lockTitle + tbPlaceBespeak.getPlaceId());
//设置锁超时时间,防止异常造成死锁
rlock.lock(20, TimeUnit.SECONDS);
try {
//业务
}catch (Exception e){
throw new CustomException(e.getMessage());
}finally {
//释放锁
rlock.unlock();
}