创建分布式锁

private static final String LOCK_SUCCESS = "OK";
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_WITH_EXPIRE_TIME = "EX";
private static final Long RELEASE_SUCCESS = 1L;

private static final String LVCC_LEDGER_LOCK = "lvcc:ledger:lock:";

/**
* 尝试加分布式锁
*
* @param lockKey 锁名称
* @param requestId 请求标识
* @param expireTime 超期时间 单位秒
* @return 是否加锁成功
*/
public boolean setDcsLock(String lockKey, String requestId, int expireTime) {
RedisConnection conn = RedisConnectionUtils.getConnection(redisTemplate.getConnectionFactory());
Jedis jedis = (Jedis) conn.getNativeConnection();
String result = jedis.set(LVCC_LEDGER_LOCK + lockKey, requestId,
SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
if (LOCK_SUCCESS.equals(result)) {
return true;
}
return false;
}

/**
* 释放分布式锁
*
* @param lockKey 锁名称
* @param requestId 请求标识
* @return 是否释放成功
*/
public boolean delDcsLock(String lockKey, String requestId) {
RedisConnection conn = RedisConnectionUtils.getConnection(redisTemplate.getConnectionFactory());
Jedis jedis = (Jedis) conn.getNativeConnection();
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(LVCC_LEDGER_LOCK + lockKey),
Collections.singletonList(requestId));
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
return false;
}
posted @ 2021-03-09 16:24  高小憨  阅读(42)  评论(0)    收藏  举报