1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
public class RedisLockImpl implements RedisLock {
private static final String REDIS_LOCK_NAME_PREFIX = "REDIS_LOCK_"; private static final String LOCK_SUCCESS = "OK";
private static final String SET_IF_NOT_EXIST = "NX"; private static final String SET_WITH_EXPIRE_TIME = "PX";
private static final long DEFAULT_TIMEOUT_MILLISECOND = 1000 * 60 * 10;
@Override public String tryLock(String lockName, long timeout) { if (Objects.isNull(lockName)) return null; Jedis jedis = null; try { jedis = jedisPool.getResource(); String value = UUID.randomUUID().toString(); String key = REDIS_LOCK_NAME_PREFIX + lockName; String result = jedis.set(key, value, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, timeout); if (LOCK_SUCCESS.equals(result)){ return value; } }catch (Exception e){ System.err.printf("获取锁失败,lockName:%s", lockName); }finally { if (Objects.nonNull(jedis)){ jedis.close(); } }
return null; }
@Override public String tryLock(String lockName) { return tryLock(lockName, DEFAULT_TIMEOUT_MILLISECOND); }
@Override public boolean unLock(String lockName, String identifier) { if (Objects.isNull(lockName) || Objects.isNull(identifier)) return false;
Jedis jedis = null; String key = REDIS_LOCK_NAME_PREFIX + lockName; try { jedis = jedisPool.getResource(); StringBuilder script = new StringBuilder(); script.append("if redis.call('get','").append(key).append("')").append("=='").append(identifier).append("'"). append(" then "). append(" return redis.call('del','").append(key).append("')"). append(" else "). append(" return 0"). append(" end"); return Integer.parseInt(jedis.eval(script.toString()).toString()) > 0 ? true : false; }catch (Exception e){ System.err.printf("释放锁失败,lockName:%s,identifier:%s", lockName, identifier); }finally { if (Objects.nonNull(jedis)){ jedis.close(); } } return false; } }
|