Redis
同一请求只会成功一个
:为解决超卖问题,200个请求同时访问只会有一个请求成功
@GetMapping("seckill")
public void seckill(){
Object o = redisTemplate.execute(new SessionCallback<Object>() {
@Override
public Object execute(RedisOperations redisOperations) {
redisOperations.watch("kc");//监控库存
Object kc = redisOperations.opsForValue().get("kc");//获取库存
Random random = new Random();
int id = random.nextInt(5000);//生成随机ID
if (kc == null) {
return "秒杀还没开始";
}
if (Integer.parseInt(kc.toString()) <= 0) {
return "秒杀结束了";
}
if(redisOperations.opsForSet().isMember("user",id)){
return "不可重复秒杀";
}
redisOperations.multi();//开启事务
try {
redisOperations.opsForValue().decrement("kc");
redisOperations.opsForSet().add("user",id);
} catch (Exception e) {
System.out.println("并发触发事务");
}
return redisOperations.exec();
}
});
System.out.println(o);
//System.out.println(redisTemplate.opsForValue().get("k1"));
}