Java 版本的基于Jedis 的 Redis 分布式锁实现
锁实现
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
| 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";
public boolean tryGetDistributedLock(String lockKey, String requestId, int expireTime) { try (Jedis resource = jedisPool.getResource()) { String result = resource.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime); if (LOCK_SUCCESS.equals(result)) { return true; } } catch (Exception e) { e.printStackTrace(); return false; } return false; }
public boolean unLockByLua(String lockKey, String requestId) { String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; try (Jedis resource = jedisPool.getResource()) { Object result = resource.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId)); if (Objects.equals(1, result)) { return true; } } return false; }
|
使用方式
1 2 3 4 5 6 7 8 9 10 11
| try{
if(!tryGetDistributedLock(lock,requestId,timeout)){ throw new MyException("锁等待",403); } ...需要锁的内容 }catch(Exception e){ ...异常捕捉 }finnaly{ unLockByLua(lockKey,requestId); }
|