redis分布式锁工具类

/**
 * @ClassName RedisLock
 * @Description redis分布式锁服务
 * @Author zyy
 */
@Component
public class RedisLockService {

  private static final String LOCK_SUCCESS = "OK";
  private static final Long UNLOCK_SUCCESS = 1L;
  private static final String SET_IF_NOT_EXIST = "NX";
  private static final String SET_WITH_EXPIRE_TIME = "EX";
  private static final String RELEASE_LOCK_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";


  @Resource
  private StringRedisTemplate stringRedisTemplate;

  /**
   * 获取锁
   * @param lockKey
   * @param value
   * @param expireTime:单位-秒
   * @return
   */
  public boolean getLock(String lockKey, String value, int expireTime){
    return stringRedisTemplate.execute((RedisCallback<Boolean>) redisConnection -> {
      Jedis jedis = (Jedis) redisConnection.getNativeConnection();
      String result = jedis.set(lockKey, value, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
      if (LOCK_SUCCESS.equals(result)) {
        return Boolean.TRUE;
      }
      return Boolean.FALSE;
    });
  }

  /**
   * 释放锁
   * @param lockKey
   * @param value
   * @return
   */
  public boolean unLock(String lockKey, String value) {
    return stringRedisTemplate.execute((RedisCallback<Boolean>) redisConnection -> {
      Jedis jedis = (Jedis) redisConnection.getNativeConnection();
      Long result = (Long) jedis.eval(RELEASE_LOCK_SCRIPT, Collections.singletonList(lockKey),
          Collections.singletonList(value));
      if (UNLOCK_SUCCESS.equals(result)) {
        return Boolean.TRUE;
      }
      return Boolean.FALSE;
    });
  }

  /**
   * 获取分布式锁
   * @param lockKey
   */
  public boolean tryLock(String lockKey, String lockValue){
    return this.getLock(lockKey, lockValue, Constants.THIRTY_SECONDS);
  }

  /**
   * 获取分布式锁
   * @param lockKey
   * @param lockValue
   * @param lockTime
   * @return
   */
  public boolean tryLock(String lockKey, String lockValue, int lockTime){
    return this.getLock(lockKey, lockValue, lockTime);
  }

  /**
   * 解锁
   * @param lockKey
   */
  public void removeLock(String lockKey, String lockValue){
    try {
      this.unLock(lockKey, lockValue);
    }catch (Exception e){
      throw new FinanceFastFailException("解锁失败 lockKey" + lockKey);
    }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Carl God

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值