Redis实战--Jedis实现分布式锁

2019-11-19 来源: xlecho 发布在  https://www.cnblogs.com/xlecho/p/11886884.html

echo编辑整理,欢迎转载,转载请声明文章来源。欢迎添加echo微信(微信号:t2421499075)交流学习。 百战不败,依不自称常胜,百败不颓,依能奋力前行。——这才是真正的堪称强大!!!


分布式锁的基本要求

  • 互斥
  • 没有死锁
  • 我持有的锁只能被我释放

分布式锁的释放和获取代码实现

package com.example.echo.redis.distlock;

import redis.clients.jedis.Jedis;

import java.util.Collections;

/**
 * @author XLecho
 * Date 2019/11/18 0018
 * Time 21:14
 */
public class DistLock {

    private static final String LOCK_SUCCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";
    private static final Long RELEASE_SUCCESS = 1L;

    /**
     * 尝试获取分布式锁
     *
     * @param jedis      redis客户端
     * @param lockKey    锁
     * @param requestId  请求标识
     * @param expireTime 超时时间
     * @return
     */
    public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) {
        String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
        return LOCK_SUCCESS.equals(result);
    }

    /**
     * 释放分布式锁
     *
     * @param jedis     redis客户端
     * @param lockKey   锁
     * @param requestId 请求标识
     * @return
     */
    public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
        return RELEASE_SUCCESS.equals(result);
    }

}

做一个有底线的博客主

相关文章