/**
* ms
*/
public static final int LOCK_EXPIRE = 1000 * 60 ;
private static final Long SUCCESS = 1L;
public boolean tryLock(String lockKey, String value) {
return tryLock(lockKey, value, LOCK_EXPIRE);
}
/**
* 获取锁
*
* @param lockKey
* @param value
* @param expireTime:单位-秒
* @return
*/
public boolean tryLock(String lockKey, String value, int expireTime) {
try {
/* String script = "if redis.call('setNx',KEYS[1],ARGV[1]) then if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('expire',KEYS[1],ARGV[2]) else return 0 end end";*/
String script = "if redis.call('setNx',KEYS[1],ARGV[1])==1 then\n" +
" if redis.call('get',KEYS[1])==ARGV[1] then\n" +
" return redis.call('expire',KEYS[1],ARGV[2])\n" +
" else\n" +
" return 0\n" +
" end\n" +
"else\n" +
" return 0\n" +
"end";
RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), value, expireTime);
if (SUCCESS.equals(result)) {
return true;
}
} catch (Exception e) {
log.error("获取锁错误:lockKey{}, value:{}, expireTime:{}, e:{}", lockKey, value, expireTime, e);
}
return false;
}
/**
* <p>释放锁</p>
*
* @param lockKey
* @param value
* @return
*/
public boolean releaseLock(String lockKey, String value) {
try {
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), value);
if (SUCCESS.equals(result)) {
return true;
}
} catch (Exception e) {
log.error("释放锁错误:lockKey{}, value:{}, e:{}", lockKey, value, e);
}
return false;
}
/**
* redis 获取关键key操作
* @param lockKey
* @param args
* @param script
* @return
*/
private Object redisExecute(String lockKey, List<String> args, String script){
Object result = redisTemplate.execute((RedisCallback<Long>) connection -> {
Object nativeConnection = connection.getNativeConnection();
if (nativeConnection instanceof JedisCluster) {
return (Long) ((JedisCluster) nativeConnection).eval(script, Collections.singletonList(lockKey), args);
} else if (nativeConnection instanceof Jedis) {
return (Long) ((Jedis) nativeConnection).eval(script, Collections.singletonList(lockKey), args);
}
return null;
});
return result;
Redis 的学习笔记 18 RedisTemplate 实现分布式锁
最新推荐文章于 2024-07-23 10:13:59 发布