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 31 32 33 34
|
@Component public class RedisLockUtils { @Autowired private RedisTemplate redisTemplate; private static final Long LOCK_REDIS_TIMEOUT = 10L; public static final Long LOCK_REDIS_WAIT = 500L;
public Boolean getLock(String key,String value){ Boolean lockStatus = this.redisTemplate.opsForValue().setIfAbsent(key,value, Duration.ofSeconds(LOCK_REDIS_TIMEOUT)); return lockStatus; }
public Long releaseLock(String key,String value){ String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript,Long.class); Long releaseStatus = (Long)this.redisTemplate.execute(redisScript, Collections.singletonList(key),value); return releaseStatus; } }
|