redis锁示例
@Component
public class RedisService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
/***
* 加锁
* @param key
* @param value 当前时间+超时时间
* @return 锁住返回true
*/
public boolean lock(String key,String value){
if(stringRedisTemplate.opsForValue().setIfAbsent(key,value)){//setNX 返回boolean
return true;
}
//如果锁超时 ***
String currentValue = stringRedisTemplate.opsForValue().get(key);
if(!StringUtils.isEmpty(currentValue) && Long.parseLong(currentValue)<System.currentTimeMillis()){
//获取上一个锁的时间
String oldvalue = stringRedisTemplate.opsForValue().getAndSet(key,value);
if(!StringUtils.isEmpty(oldvalue)&&oldvalue.equals(currentValue)){
return true;
}
}
return false;
}
/***
* 解锁
* @param key
* @param value
* @return
*/
public void unlock(String key,String value){
try {
String currentValue = stringRedisTemplate.opsForValue().get(key);
if(!StringUtils.isEmpty(currentValue)&¤tValue.equals(value)){
stringRedisTemplate.opsForValue().getOperations().delete(key);
}
} catch (Exception e) {
log.error("解锁异常");
}
}
}
秒杀示例
private static final int TIMEOUT= 10*1000;
@Transactional
public void orderProductMockDiffUser(String productId){
long time = System.currentTimeMillions()+TIMEOUT;
if(!redislock.lock(productId,String.valueOf(time)){
throw new SellException(101,"换个姿势再试试")
}
//1.查库存
int stockNum = stock.get(productId);
if(stocknum == 0){
throw new SellException(ProductStatusEnum.STOCK_EMPTY);
}else{
//2.下单
orders.put(KeyUtil.genUniqueKey(),productId);//生成随机用户id模拟高并发
sotckNum = stockNum-1;
try{
Thread.sleep(100);
} catch (InterruptedExcption e){
e.printStackTrace();
}
stock.put(productId,stockNum);
}
redisLock.unlock(productId,String.valueOf(time));
}
redis锁实现秒杀
最新推荐文章于 2024-06-16 15:00:00 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)