Mark StringRedisTemplate distributed lock for personal use
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);
If this code construction method does not add the second parameter, the following error will be reported
Unknown redis exception; nested exception is java.lang.IllegalStateException: io.lettuce.core.output.ValueOutput does not support set(long)
Then just add it