redis可重入锁

package com.example.demo.util;

import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: lihaozhen
 * @Date: 2020/6/20 23:12
 * @Description:redis 可重如锁
 */
public class RedisWitReentrantLock {
    private ThreadLocal<Map<String,Integer>> lockers = new ThreadLocal<>();
    private Jedis jedis;

    public RedisWitReentrantLock(Jedis jedis){
        this.jedis = jedis;
    }
    private boolean _lock(String key){
        return jedis.set(key,"","nx","ex",5L) != null;
    }
    private void _unlock(String key){
        jedis.del(key);
    }
    private Map<String,Integer> currentLocakers(){
        Map<String,Integer> refs = lockers.get();
        if (refs != null){
            return refs;
        }
        lockers.set(new HashMap<>());
        return lockers.get();
    }
    public boolean lock(String key){
        Map<String,Integer>refs = currentLocakers();
        Integer refCnt = refs.get(key);
        if (refCnt!= null){
            refs.put(key,refCnt+1);
            return true;
        }
        boolean ok = this._lock(key);
        if (!ok){
            return false;
        }
        refs.put(key,1);
        return true;
    }
    public boolean unlock(String key){
        Map<String,Integer> refs = currentLocakers();
        Integer refCnt = refs.get(key);
        if (refCnt == null){
            return false;
        }
        refCnt -= 1;
        if (refCnt> 0){
            refs.put(key,refCnt);
        }else {
            refs.remove(key);
            this._unlock(key);
        }
        return true;
    }

    public static void main(String[] args) {
        Jedis jedis = new Jedis();
        RedisWitReentrantLock redis = new RedisWitReentrantLock(jedis);
        System.out.println(redis.lock("lihaozhen"));
        System.out.println(redis.lock("lihaozhen"));
        System.out.println(redis.unlock("lihaozhen"));
        System.out.println(redis.unlock("lihaozhen"));
    }
}

依赖

 <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.3</version>
        </dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值