redis加锁解锁 代码实现
@Service
public class RedisLockService {
private static final Long SUCCESS = 1L;
@Resource
private RedisTemplate<String, Object> redisTemplate;
public boolean lock(String key, String value, int millisecond, int tryCount) {
if (tryCount > 5) {
tryCount = 5;
}
try {
String script =
"local key = KEYS[1]; local value = ARGV[1]; if redis.call('set', key, value, 'NX' ,'PX', "
+ millisecond + ") then return 1 else return 0 end";
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
Long result = redisTemplate
.execute(redisScript, Collections.singletonList(key), Collections.singletonList(value));
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
} catch (Exception ex) {
if (tryCount == 0) {
return false;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return false;
}
System.out.println(tryCount);
return lock(key, value, millisecond, tryCount - 1);
}
return false;
}
public boolean unlock(String key) {
return redisTemplate.delete(key);
}
public boolean releaseLock(String lockKey, String value) {
String script =
"if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
Long execute =
redisTemplate.execute(redisScript, Collections.singletonList(lockKey), Collections.singletonList(value));
if (RELEASE_SUCCESS.equals(execute)) {
return true;
}
return false;
}
}