123456789101112131415161718192021222324252627282930 |
- 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<String, Object> redisTemplate;
- public boolean tryLock(String lockKey, String lockValue, long expireTime, TimeUnit timeUnit) {
- ValueOperations<String, Object> valueOps = redisTemplate.opsForValue();
- Boolean result = valueOps.setIfAbsent(lockKey, lockValue, expireTime, timeUnit);
- // setIfAbsent 方法会在键不存在时设置键值对,并返回是否成功
- return result != null && result;
- }
- public void unlock(String lockKey, String lockValue) {
- ValueOperations<String, Object> valueOps = redisTemplate.opsForValue();
- // 确保只有锁的持有者才能释放锁,避免误释放
- if (lockValue.equals(valueOps.get(lockKey))) {
- redisTemplate.delete(lockKey);
- }
- }
- }
|