import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.stereotype.Component;
import java.util.Collections;
@Component public class RedisLockUtil { @Autowired private StringRedisTemplate stringRedisTemplate;
private static final String LOCK_SCRIPT = "if redis.call('setnx', KEYS[1], ARGV[1]) == 1 then " +
"return redis.call('expire', KEYS[1], ARGV[2]) else return 0 end";
private static final String UNLOCK_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then " +
"return redis.call('del', KEYS[1]) else return 0 end";
public boolean lock(String key, String value, long timeout) {
DefaultRedisScript<Long> script = new DefaultRedisScript<>(LOCK_SCRIPT, Long.class);
Long result = stringRedisTemplate.execute(script, Collections.singletonList(key), value, String.valueOf(timeout));
return result != null && result > 0;
}
public boolean unlock(String key, String value) {
DefaultRedisScript<Long> script = new DefaultRedisScript<>(UNLOCK_SCRIPT, Long.class);
Long result = stringRedisTemplate.execute(script, Collections.singletonList(key), value);
return result != null && result > 0;
}
}