redis单机部署时实现的分布式锁
/**
* @Author: zqf
* @Description:
* @Date 2021/8/25 10:08
*/
public class distributedLock {
/**
* 释放锁lua脚本,原子操作:lua脚本是作为一个整体执行的,所以中间不会被其他命令插入。
*/
private final static String RELEASE_LOCK_LUA_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
private static final Long RELEASE_SUCCESS = 1L;
/**
*
* @param lockId 锁
* @param requestId 请求标识
* @param seconds 过期时间
* @return
*/
public static boolean getLock(Redistemplate redistemplate, String lockId, String requestId, long seconds) {
Boolean success = redistemplate.opsForValue().setIfAbsent(lockId, requestId, seconds, TimeUnit.SECONDS);
return success != null && success;
}
/**
* 释放锁
* @param redistemplate
* @param lockId 锁
* @param requestId 请求标识
* @return 是否释放成功
*/
public static boolean releaseLock(Redistemplate redistemplate, String lockId, String requestId) {
// 指定 lua 脚本,并且指定返回值类型
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(RELEASE_LOCK_LUA_SCRIPT,Long.class);
// 参数一:redisScript,参数二:key列表,参数三:arg(可多个)
Long result = (Long) redistemplate.execute(redisScript, Collections.singletonList(lockId), requestId);
return RELEASE_SUCCESS.equals(result);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。