当前位置: 代码迷 >> 综合 >> java redis分布式锁
  详细解决方案

java redis分布式锁

热度:43   发布时间:2024-01-26 04:06:53.0

public class RedisDistributedLock {private static final String LOCK_SUCCESS = "OK";private static final Long RELEASE_SUCCESS = 1L;private static int WAIT_TIME = 1 * 1000;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;}public boolean release(Jedis jedis,String key,String value) {if (value == null) {return false;}return false;}
}