可重入分布式锁-redis实现

这个博客介绍了如何使用Redis实现一个可重入锁。通过Java代码展示了如何使用Jedis客户端进行加锁、解锁操作,并且包含重试机制以防止锁超时。还涉及到本地缓存来处理重入情况,并使用Lua脚本来保证原子性操作。
摘要由CSDN通过智能技术生成

public class RedisReentrantLock {

    private static final String script =
            "if (ARGV[1] = redis.call('get', KEYS[1])) " +
            "then " +
                    "redis.call('del', KEYS[1]) " +
                    "return 1; " +
            "else " +
                    "return 0; " +
            "end";

    private static final ThreadLocal<Map<String, Integer>> tl = ThreadLocal.withInitial(HashMap::new);

    private static final Map<String, String> valueCache = new HashMap<>();

    private static final String cacheKeyPatten = "threadId-%d-%s";

    private final Jedis jedis;

    public RedisReentrantLock(Jedis jedis) {
        this.jedis = jedis;
    }

    private Map<String, Integer> getLocks() {
        return tl.get();
    }

    public void unLock(String key) {
        //key集合
        Map<String, Integer> locks = getLocks();
        //若存在重入,就减小
        Integer num = locks.get(key);
        if (num > 1) {
            locks.computeIfPresent(key, (k, v) -> --v);
        }else {
            //不存在重入,删除key
            String value = valueCache.get(String.format(cacheKeyPatten, Thread.currentThread().getId(), key));
            tryLock(key,value);
            locks.remove(key);
        }
    }

    public void tryLock(String key, String value) {
        jedis.eval(script, 1, key, value);
    }

    public boolean lock(String key, long timeout, TimeUnit timeUnit) {
        return lock(key, 5, TimeUnit.SECONDS, timeout, timeUnit);
    }

    public boolean lock(String key, long redisKeyTimeout, TimeUnit cacheKeyTimeUnit, long timeout, TimeUnit timeUnit) {
        //检查本地是否已存在
        Map<String, Integer> locks = getLocks();
        if (locks.containsKey(key)) {
            locks.computeIfPresent(key, (k, v) -> ++v);
            return true;
        } else {
            long endTime = System.currentTimeMillis() + timeUnit.toMillis(timeout);
            String uuid = UUID.randomUUID().toString();
            while (true) {

                //尝试获取锁
                if (tryLock(key, uuid, cacheKeyTimeUnit.toSeconds(redisKeyTimeout))) {
                    locks.put(key, 1);
                    //缓存redis中的value,在释放锁的时候检查是否是同一把锁
                    valueCache.put(String.format(cacheKeyPatten, Thread.currentThread().getId(), key), uuid);
                    return true;
                }

                //获取锁超时
                if (System.currentTimeMillis() > endTime) {
                    return false;
                }

                //等待500ms
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public boolean tryLock(String key,String value, long timeout) {
        String ret = jedis.set(key, value, "nx", "ex", timeout);
        return null != ret;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值