前言
用于分布式程序彼此之间不能同时执行的场景。例如计算程序等。
代码
锁工具类
@Component
public class RedisLockUtil {
@Autowired
private RedisTemplate redisTemplate;
private static final String CALC_LOCK_KEY = "CalculateLock";
private static final Long CALC_LOCK_TIME = 30L;
public boolean setIfAbsent (String key,String value,Long lockTime) {
return redisTemplate.opsForValue().setIfAbsent(key,value,lockTime,TimeUnit.MINUTES);
}
public String getValue(String key) {
return (String) redisTemplate.opsForValue().get(key);
}
public void delete (String key) {
redisTemplate.delete(key);
}
public boolean calcLock (String value) {
return redisTemplate.opsForValue().setIfAbsent(CALC_LOCK_KEY,value,CALC_LOCK_TIME,TimeUnit.MINUTES);
}
public String getCalcValue () {
return (String) redisTemplate.opsForValue().get(CALC_LOCK_KEY);
}
public String getTimeSeed(){
return String.valueOf(new Date().getTime());
}
public void unCalclock () {
redisTemplate.delete(CALC_LOCK_KEY);
}
}
实际调用的代码
@PostMapping("/calc")
public void calc() throws Exception{
String redisValue = "计算"+redisLockUtil.getTimeSeed();
boolean flag = redisLockUtil.calcLock(redisValue);
if(!flag){
return ;
}
try{
//业务代码
}catch (Exception e){
e.printStackTrace();
//业务代码
return ;
}finally {
//为了防止过期导致删除了其他人的锁
if(redisValue.equals(redisLockUtil.getCalcValue())){
redisLockUtil.unCalclock();
}
}
return;
}