Redis实现可重入分布式锁

package com.ccf.service.lock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Component
public class RedisLock {

    Logger logger = LoggerFactory.getLogger(RedisLock.class);

    @Resource
    private RedisTemplate redisTemplate;

    //处理可重入的问题
    ThreadLocal> threadLocal = ThreadLocal.withInitial(HashMap::new);

    /**
     *
     * @param lockKey 分布式锁key
     * @param requestId 锁的值
     * @param acquireTimeout 尝试获取锁的超时时间,单位毫秒
     * @param expireTime 锁的过期时间,单位毫秒
     * @return
     */
    public boolean tryLock(String lockKey,String requestId,long acquireTimeout,long expireTime){
        Map value = threadLocal.get();
        if(value.containsKey(lockKey)){
            value.put(lockKey,value.get(lockKey) + 1);
            return true;
        }
        long end = System.currentTimeMillis() + acquireTimeout;
        while(System.currentTimeMillis() < end){
            Boolean result = redisTemplate.boundValueOps(lockKey).setIfAbsent(requestId,expireTime, TimeUnit.MILLISECONDS);

            if (result) {
                value.put(lockKey,1);
                return true;
            }
            try {
                //尝试获取锁失败,休眠10ms再试
                Thread.sleep(10);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                logger.error("RedisLock中断异常",e);
                return false;
            }
        }
        return false;
    }


    /**
     * 尝试释放分布式锁
     * @param lockKey
     * @param requestId
     */
    public void tryRelease(String lockKey,String requestId){
        //处理可重入的问题
        Map value = threadLocal.get();
        //说明获取到锁的
        if(value.containsKey(lockKey)){
            Integer num = value.get(lockKey) - 1;
            if(num <= 0){
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

                DefaultRedisScript redisScript = new DefaultRedisScript<>();
                redisScript.setResultType(Long.class);
                redisScript.setScriptText(script);

                Long result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey),requestId);

                if (result.equals(1L)) {
                    value.remove(lockKey);
                }
            }else{
                value.put(lockKey,num);
            }
        }else{
            logger.warn("未获取到分布式,不能释放锁");
        }
    }

}

你可能感兴趣的:(java,java,分布式,redis)