前言
用于分布式程序彼此之间不能同时执行的场景。例如计算程序等。
代码
锁工具类
@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,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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。