RedisLock distributed redis lock
@ Component
Public class RedisLock {
Logger logger= LoggerFactory.getLogger (RedisLock.class)
Private static final String LOCK_SUCCESS = "OK"
Private static final String SET_IF_NOT_EXIST = "NX"; / / NX is millisecond, EX is second
Private static final String SET_WITH_EXPIRE_TIME = "PX"
/ * attempt to acquire distributed lock * @ param lockKey lock * @ param requestId request ID * @ param expireTime timeout * @ return obtained successfully * / public boolean tryGetDistributedLock (String lockKey, String requestId, int expireTime) {Jedis jedis=null; try {jedis= Const.jedisPoolCommon.getResource (); String result = jedis.set (lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime) If (LOCK_SUCCESS.equals (result)) {return true;}} catch (Exception ex) {logger.error ("tryGetDistributedLock exception" + ex);} finally {if (jedished exception null) {jedis.close ();}} return false;} private static final Long RELEASE_SUCCESS = 1L / * * release distributed lock * @ param lockKey lock * @ param requestId request identifies whether @ return has been successfully released * / public boolean releaseDistributedLock (String lockKey, String requestId) {Jedis jedis= null; try {jedis=Const.jedisPoolCommon.getResource (); String script = "if redis.call ('get', KEYS [1]) = ARGV [1] then return redis.call (' del', KEYS [1]) else return 0 end" Object result = jedis.eval (script, Collections.singletonList (lockKey), Collections.singletonList (requestId)); if (RELEASE_SUCCESS.equals (result)) {return true;}} catch (Exception ex) {logger.error ("releaseDistributedLock exception" + ex);} finally {if (jedised exception null) {jedis.close ();}} return false;}
}