Mark一下 StringRedisTemplate 分布式锁 自用
private static final String RELEASE_LOCK_SCRIPTS = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
@Resource(name = "stringRedisTemplate")
private StringRedisTemplate stringRedisTemplate;
public Boolean tryLock(String key,String requestId,int ttlSeconds){
return stringRedisTemplate.opsForValue().setIfAbsent(key,requestId,(long)ttlSeconds, TimeUnit.SECONDS);
}
public boolean releaseLock(String key,String requestId){
// RedisScript<Long> redisScript = new DefaultRedisScript<>(RELEASE_LOCK_SCRIPTS);
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(RELEASE_LOCK_SCRIPTS,Long.class);
Long result = stringRedisTemplate.execute(redisScript, Arrays.asList(key), requestId);
if(result != null && result.intValue() == 1){
return true;
}
return false;
}
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(RELEASE_LOCK_SCRIPTS,Long.class);
这一句代码构造方法如果不加第二个参数,会报以下错误
Unknown redis exception; nested exception is java.lang.IllegalStateException: io.lettuce.core.output.ValueOutput does not support set(long)
那么加上就可以了