RedisLock.java 1.1 KB

123456789101112131415161718192021222324252627282930
  1. package com.tzld.piaoquan.longarticle.component;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.data.redis.core.RedisTemplate;
  4. import org.springframework.data.redis.core.ValueOperations;
  5. import org.springframework.stereotype.Component;
  6. import java.util.concurrent.TimeUnit;
  7. @Component
  8. public class RedisLock {
  9. @Autowired
  10. private RedisTemplate<String, Object> redisTemplate;
  11. public boolean tryLock(String lockKey, String lockValue, long expireTime, TimeUnit timeUnit) {
  12. ValueOperations<String, Object> valueOps = redisTemplate.opsForValue();
  13. Boolean result = valueOps.setIfAbsent(lockKey, lockValue, expireTime, timeUnit);
  14. // setIfAbsent 方法会在键不存在时设置键值对,并返回是否成功
  15. return result != null && result;
  16. }
  17. public void unlock(String lockKey, String lockValue) {
  18. ValueOperations<String, Object> valueOps = redisTemplate.opsForValue();
  19. // 确保只有锁的持有者才能释放锁,避免误释放
  20. if (lockValue.equals(valueOps.get(lockKey))) {
  21. redisTemplate.delete(lockKey);
  22. }
  23. }
  24. }