package com.tzld.piaoquan.longarticle.component; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; @Component public class RedisLock { @Autowired private RedisTemplate redisTemplate; public boolean tryLock(String lockKey, String lockValue, long expireTime, TimeUnit timeUnit) { ValueOperations valueOps = redisTemplate.opsForValue(); Boolean result = valueOps.setIfAbsent(lockKey, lockValue, expireTime, timeUnit); // setIfAbsent 方法会在键不存在时设置键值对,并返回是否成功 return result != null && result; } public void unlock(String lockKey, String lockValue) { ValueOperations valueOps = redisTemplate.opsForValue(); // 确保只有锁的持有者才能释放锁,避免误释放 if (lockValue.equals(valueOps.get(lockKey))) { redisTemplate.delete(lockKey); } } }