java redis分布式锁

我们两清 提交于 2020-01-26 04:42:36

public class RedisDistributedLock {
    private static final String LOCK_SUCCESS = "OK";
    private static final Long RELEASE_SUCCESS = 1L;
    private static int WAIT_TIME = 1 * 1000;
    private static String EVAL_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then  return redis.call('del', KEYS[1]) else return 0 end";
    public String lock(Jedis jedis, String key) {
        try {
            // 超过等待时间,加锁失败
            long waitEnd = System.currentTimeMillis() + WAIT_TIME;
            String value = UUID.randomUUID().toString();
            while (System.currentTimeMillis() < waitEnd) {
                String result = jedis.set(key, value, "NX", "PX", 1000);
                if (LOCK_SUCCESS.equals(result)) {
                    return value;
                }
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        } catch (Exception ex) {
            log.error("lock error", ex);
        }
        return null;
    }
    //key分布式锁的key  value加锁时候那个UUID
    public boolean release(Jedis jedis,String key,String value) {
        if (value == null) {
            return false;
        }
        return RELEASE_SUCCESS.equals(JedisUtils.eval(evalscript,Collections.singletonList(key), Collections.singletonList(value)));
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!