[分享]redis increment实现分部署锁
@Autowired
private RedisTemplate redisTemplate;
/**
* 加锁
*/
public boolean getLock(String key) {
try {
long count = redisTemplate.opsForValue().increment(key, 1);
if(count == 1){
//设置有效期2秒
redisTemplate.expire(key, 2, TimeUnit.SECONDS);
return true;
}else{
long time = redisTemplate.getExpire(key,TimeUnit.SECONDS);
if(time == -1){
//设置失败重新设置过期时间
redisTemplate.expire(key, 2, TimeUnit.SECONDS);
return true;
}
}
//如果存在表示重复
return false;
} catch (Exception e) {
logger.error("redis加锁异常", e);
redisTemplate.delete(key); //出现异常删除锁
return true;
}
}
原文:https://blog.csdn.net/u011974797/article/details/81238079