工具类
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
public class RedisLockCommon {
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
* Redis加锁
*
* @param key
* @param value
* @return
*/
public Boolean Lock(String key, String value) {
if (stringRedisTemplate.opsForValue().setIfAbsent(key, value)) {
return true;
}
String currentValue = stringRedisTemplate.opsForValue().get(key);
if (StringUtils.isNotEmpty(currentValue) && Long.valueOf(currentValue) < System.currentTimeMillis()) {
//上一次上锁时间,防止高并发情况下出现的被修改问题,到达线程安全
String oldValue = stringRedisTemplate.opsForValue().getAndSet(key, value);
if (StringUtils.isNotEmpty(oldValue) && oldValue.equals(currentValue)) {
return true;
}
}
return false;
}
/**
* Redis解锁
*
* @param key
* @param value
*/
public void unlock(String key, String value) {
String currentValue = stringRedisTemplate.opsForValue().get(key);
try {
if (StringUtils.isNotEmpty(currentValue) && currentValue.equals(value)) {
stringRedisTemplate.opsForValue().getOperations().delete(key);
}
} catch (Exception e) {
}
}
}
用法
//redis判定是否可购买,并加入缓存
String key = "test";
long time = System.currentTimeMillis();
try {
//加锁失败
if (!redisLock.Lock(key, String.valueOf(time))) {
return "加锁失败!!!";
}
//逻辑
} catch (Exception e) {
e.printStackTrace();
} finally {
//解锁
redisLock.unlock(key, String.valueOf(time));
}