Redis分布式锁基于JEDIS和Spring BOOT

本文只有代码,具体的锁概念什么的可以搜一下,代码加入项目后,记得验证一下,不要坑到大家就行。

1、基于JEDIS


  // 分布式锁
  /**
   * LOCK_SUCCESS:成功加锁.
   * 
   * @since JDK 1.8
   */
  private static final String LOCK_SUCCESS = "OK";
  /**
   * SET_IF_NOT_EXIST:NX,意思是SET IF NOT
   * EXIST,即当key不存在时,我们进行set操作;若key已经存在,则不做任何操作;.
   * 
   * @since JDK 1.8
   */
  private static final String SET_IF_NOT_EXIST = "NX";
  /**
   * SET_WITH_EXPIRE_TIME:PX,意思是我们要给这个key加一个过期的设置,具体时间由第五个参数决定。.
   * 
   * @since JDK 1.8
   */
  private static final String SET_WITH_EXPIRE_TIME = "PX";
  /**
   * RELEASE_SUCCESS:成功解锁标志.
   * 
   * @since JDK 1.8
   */
  private static final Long RELEASE_SUCCESS = 1L;

  /**
   * tryGetDistributedLock:尝试获取分布式锁. <br/>
   *
   * @author atc
   * @param lockKey
   *          锁
   * @param requestId
   *          请求标识
   * @param expireTime
   *          锁过期时间(自动删除,单位毫秒)
   * @return 是否加锁成功
   * @since JDK 1.8
   */
  public boolean tryGetDistributedLock(String lockKey, String requestId,
      int expireTime) {
    Jedis jedis = null;
    try {
      jedis = jedisPool.getResource();
      String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST,
          SET_WITH_EXPIRE_TIME, expireTime);
      if (LOCK_SUCCESS.equals(result)) {
        return true;
      }
      return false;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    } finally {
      if (null != jedis) {
        jedis.close();
      }
    }
  }

  /**
   * releaseDistributedLock:释放分布式锁. <br/>
   *
   * @author atc
   * @param lockKey
   *          锁
   * @param requestId
   *          请求标识
   * @return 是否解锁成功
   * @since JDK 1.8
   */
  public boolean releaseDistributedLock(String lockKey, String requestId) {
    Jedis jedis = null;
    try {
      jedis = jedisPool.getResource();
      // 判断锁是否存在
      if (jedis.exists(lockKey)) {
        // 存在则解锁
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return "
            + "redis.call('del', KEYS[1]) else return 0 end";

        Long result = (Long) jedis.eval(script,
            Collections.singletonList(lockKey),
            Collections.singletonList(requestId));
        if (RELEASE_SUCCESS.equals(result)) {
          return true;
        }
        return false;
      } else {
        return true;
      }
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    } finally {
      if (null != jedis) {
        jedis.close();
      }
    }
  }

2、基于SPRING BOOT

// 分布式锁

  /**
   * RELEASE_SUCCESS:成功解锁标志.
   * 
   * @since JDK 1.8
   */
  private static final Long RELEASE_SUCCESS = 1L;

  /**
   * tryGetDistributedLock:尝试获取分布式锁. <br/>
   *
   * @author atc
   * @param lockKey
   *          锁
   * @param requestId
   *          请求标识
   * @param expireTime
   *          锁过期时间(自动删除,单位毫秒)
   * @return 是否加锁成功
   * @since JDK 1.8
   */
  public boolean tryGetDistributedLock(String lockKey, String requestId,
      int expireTime) {
    try {
      return stringRedisTemplate.opsForValue().setIfAbsent(lockKey, requestId,
          expireTime, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

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

  /**
   * releaseDistributedLock:释放分布式锁. <br/>
   *
   * @author atc
   * @param lockKey
   *          锁
   * @param requestId
   *          请求标识
   * @return 是否解锁成功
   * @since JDK 1.8
   */
  public boolean releaseDistributedLock(String lockKey, String requestId) {
    try {
      // 判断锁是否存在
      if (exists(lockKey)) {
        // 存在则解锁
        Object execute = redisTemplate.execute(
            (RedisConnection connection) -> connection.eval(script.getBytes(),
                org.springframework.data.redis.connection.ReturnType.INTEGER, 1,
                lockKey.getBytes(), requestId.getBytes()));
        return RELEASE_SUCCESS.equals(execute);
      } else {
        return true;
      }
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章