项目中有用到 redis 的分布式锁吗?是怎么实现的?
/**
* 加锁
* @param key redis key
* @param expire 过期时间,单位秒
* @return true:加锁成功,false,加锁失败
*/
public static boolean lock(String key, int expire) {
RedisService redisService = SpringUtils.getBean(RedisService.class);
long value = System.currentTimeMillis() + expire;
long status = redisService.setnx(key, String.valueOf(value));
if(status == 1) {
return true;
}
long oldExpireTime = Long.parseLong(redisService.get(key, "0"));
//如果之前设置的超时时间比当前时间小,说明之前设置的那个锁没有意义了
if(oldExpireTime < System.currentTimeMillis()) {
//超时
long newExpireTime = System.currentTimeMillis() + expire;
long currentExpireTime = Long.parseLong(redisService.getSet(key, String.valueOf(newExpireTime)));
//将redis里面保存的值和之前获取到的时间比较,相同表示没有被别人锁住
if(currentExpireTime == oldExpireTime) {
return true;
}
}
return false;
}