public final class RedisLockUtil {
private static final int defaultExpire = 60;
/**
* 加锁
* @param key redis key
* @param expire 过期时间,单位秒
* @return true:加锁成功,false,加锁失败
*/
public static boolean lock2(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;
}
//如果没有设置成功 的后获取锁的value
long oldExpireTime = Long.parseLong(redisService.get(key, "0"));
if(oldExpireTime < System.currentTimeMillis()) {
//超时
long newExpireTime = System.currentTimeMillis() + expire;
//用getset覆盖 (getset理解为先get,再set。get的是旧的值,set的是新的值。)
long currentExpireTime = Long.parseLong(redisService.getSet(key, String.valueOf(newExpireTime)));
if(currentExpireTime == oldExpireTime) {
return true;
}
}
return false;
}
public static void unLock2(String key) {
RedisService redisService = SpringUtils.getBean(RedisService.class);
long oldExpireTime = Long.parseLong(redisService.get(key, "0"));
//oldExpireTime = 原当前时间 + 过期时间 其实不大于当前时间 都已经过期了
if(oldExpireTime > System.currentTimeMillis()) {
redisService.del(key);
}
}
}