RedisLock.java 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package jnpf.flowable.util;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.data.redis.core.RedisTemplate;
  4. import org.springframework.data.redis.core.script.DefaultRedisScript;
  5. import org.springframework.data.redis.core.script.RedisScript;
  6. import org.springframework.stereotype.Component;
  7. import java.util.Collections;
  8. import java.util.concurrent.TimeUnit;
  9. /**
  10. * 类的描述
  11. *
  12. * @author JNPF@YinMai Info. Co., Ltd
  13. * @version 5.0.x
  14. * @since 2025/1/9 14:19
  15. */
  16. @Component
  17. public class RedisLock {
  18. private static final String LOCK_KEY_PREFIX = "workflow-lock:";
  19. @Autowired
  20. private RedisTemplate<String, Object> redisTemplate;
  21. private String getLockKey(String lockName) {
  22. return LOCK_KEY_PREFIX + lockName;
  23. }
  24. // false表示设置失败
  25. public boolean lock(String lockName, String lockValue, long expireTime, TimeUnit unit) {
  26. Boolean result = redisTemplate.opsForValue().setIfAbsent(getLockKey(lockName), lockValue, unit.toSeconds(expireTime), TimeUnit.SECONDS);
  27. return result != null && result;
  28. }
  29. public boolean unlock(String lockName, String lockValue) {
  30. String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
  31. RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
  32. Long result = redisTemplate.execute(redisScript, Collections.singletonList(getLockKey(lockName)), Collections.singletonList(lockValue));
  33. return result != null && result > 0;
  34. }
  35. }