package me.chanjar.weixin.common.util.locks;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

import com.github.jedis.lock.JedisLock;
import me.chanjar.weixin.common.error.WxRuntimeException;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.util.Pool;

/**
 * JedisPool 分布式锁
 *
 * @author <a href="https://github.com/007gzs">007</a>
 */
public class JedisDistributedLock implements Lock {
  private final Pool<Jedis> jedisPool;
  private final JedisLock lock;

  public JedisDistributedLock(Pool<Jedis> jedisPool, String key){
    this.jedisPool = jedisPool;
    this.lock = new JedisLock(key);
  }

  @Override
  public void lock() {
    try (Jedis jedis = jedisPool.getResource()) {
      if (!lock.acquire(jedis)) {
        throw new WxRuntimeException("acquire timeouted");
      }
    } catch (InterruptedException e) {
      throw new WxRuntimeException("lock failed", e);
    }
  }

  @Override
  public void lockInterruptibly() throws InterruptedException {
    try (Jedis jedis = jedisPool.getResource()) {
      if (!lock.acquire(jedis)) {
        throw new WxRuntimeException("acquire timeouted");
      }
    }
  }

  @Override
  public boolean tryLock() {
    try (Jedis jedis = jedisPool.getResource()) {
      return lock.acquire(jedis);
    } catch (InterruptedException e) {
      throw new WxRuntimeException("lock failed", e);
    }
  }

  @Override
  public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
    try (Jedis jedis = jedisPool.getResource()) {
      return lock.acquire(jedis);
    }
  }

  @Override
  public void unlock() {
    try (Jedis jedis = jedisPool.getResource()) {
      lock.release(jedis);
    }
  }

  @Override
  public Condition newCondition() {
    throw new WxRuntimeException("unsupported method");
  }

}

@@ -356,16 +356,57 @@
 ol %E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81%0A
+ * @deprecated %E4%B8%8D%E5%BB%BA%E8%AE%AE%E4%BD%BF%E7%94%A8jedis-lock%E8%BF%99%E4%B8%AA%E8%BF%87%E6%9C%9F%E7%BB%84%E4%BB%B6%EF%BC%8C%E4%B8%8D%E5%8F%AF%E9%9D%A0%0A
  *%0A * @a
@@ -459,16 +459,28 @@
 /a%3E%0A */%0A
+@Deprecated%0A
 public c

标记JedisLock组件为过期，不建议使用