数据库
首页 > 数据库> > redis单机部署时实现的分布式锁

redis单机部署时实现的分布式锁

作者:互联网

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);
    }
}

标签:return,String,单机,lockId,redis,param,requestId,redisTemplate,分布式
来源: https://blog.csdn.net/No_coder/article/details/119913348