使用StringRedisTemplate来实现
1.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.3.3.RELEASE</version>
</dependency>
2.加锁/解锁
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
/**
* @author chengxn
* @date 2020/7/14
*/
@Slf4j
@Component
public class RedisLock {
@Autowired
private StringRedisTemplate stringRedisTemplate;
private static final Integer MINUTES = 3 * 60 * 1000;
/**
* 加锁
*
* @param key
* @param timeStamp
* @return
*/
public boolean lock(String key, String timeStamp) {
// 对应setnx命令
if (stringRedisTemplate.opsForValue().setIfAbsent(key, timeStamp)) {
return true;
}
// 判断锁超时 - 防止原来的操作异常,没有运行解锁操作 防止死锁
String currentLock = stringRedisTemplate.opsForValue().get(key);
// 如果锁过期 currentLock不为空且超过3分钟
if (!Strings.isNullOrEmpty(currentLock) && System.currentTimeMillis() - Long.parseLong(currentLock) > MINUTES) {
// 获取上一个锁的时间value 对应getset
String preLock = stringRedisTemplate.opsForValue().getAndSet(key, timeStamp);
// 假设两个线程同时进来这里,因为key被占用了,而且锁过期了。获取的值currentLock=A(get取的旧的值肯定是一样的),两个线程的timeStamp都是B,key都是K.锁时间已经过期了。
// 而这里面的getAndSet一次只会一个执行,也就是一个执行之后,上一个的timeStamp已经变成了B。只有一个线程获取的上一个值会是A,另一个线程拿到的值是B。
if (!Strings.isNullOrEmpty(preLock) && preLock.equals(currentLock)) {
return true;
}
}
return false;
}
/**
* 解锁
*
* @param key
*/
public void unlock(String key) {
try {
String currentValue = stringRedisTemplate.opsForValue().get(key);
if (!Strings.isNullOrEmpty(currentValue)) {
// 删除锁状态
stringRedisTemplate.opsForValue().getOperations().delete(key);
}
} catch (Exception e) {
log.error("解锁异常{}", e);
}
}
}