java redis分布式锁实现

分布式锁原理和使用网上一堆,直接上代码

package com.test;

import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service("redisService")
public class RedisServiceImpl {
  
    private static final Logger logger = LoggerFactory.getLogger(RedisServiceImpl.class);
	
	
	private static final String SUCCESS = "OK";
	private static final Long RELEASE_SUCCESS = 1L;
	
	@Autowired
	private JedisPool jedisPool;
	
	
    public JedisPool getJedisPool() {
      return jedisPool;
    }
    
    public Jedis getJedis() {
      return jedisPool.getResource();
    }
    
    public String set(final String key, final String value, final String nxxx, final String expx,
        final int time) {
      try(Jedis jedis = getJedis()){
        String result = jedis.set(key, value, nxxx, expx, time);
        return result;
      }catch (Exception e) {
        logger.error("redis error:",e);
        return null;
      }
    }
    
    public boolean tryLock(String lockKey, String requestId, int expireTime) {
      String result = set(lockKey, requestId, "NX", "PX", expireTime);
      if (SUCCESS.equals(result)) {
          logger.info("{},{},tryLock分布式锁成功",lockKey,requestId);
          return true;
      }
      logger.info("{},{},tryLock分布式锁失败",lockKey,requestId);
      return false;
  }
    
    public boolean tryLock(String lockKey, String requestId, int expireTime,long timeout) {
      Long start = System.currentTimeMillis();
      for(;;) {
        boolean lock = tryLock(lockKey, requestId, expireTime);
        if(lock) {
          logger.info("获取分布式锁用时{}ms",System.currentTimeMillis() - start);
          return true;
        }
        long l = System.currentTimeMillis() - start;
        //这里重试的时候可以选择sleep
/*        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {
          throw new RuntimeException(e);
        }*/
        if (l>=timeout) {
            logger.info("{},{},{}tryLock分布式锁超时失败",lockKey,requestId,timeout);
            return false;
        }
      }
    }
    
    public  boolean unLock(String lockKey, String requestId) {
	  Long start = System.currentTimeMillis();
      String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
      try(Jedis jedis = getJedis()){
          Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
          if (RELEASE_SUCCESS.equals(result)) {
            logger.info("释放分布式锁用时{}ms",System.currentTimeMillis() - start);
            return true;
        }
        logger.info("{},{},释放分布式锁失败",lockKey,requestId);
      }catch (Exception e) {
        logger.error("redis error:",e);
      }
      return false;
  }
}

 

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