关注博主,索要git仓库完整源码

抢购前数据

库存表

微服务单体服务-抢购/秒杀超卖现象_microservices

订单表

微服务单体服务-抢购/秒杀超卖现象_mysql_02

核心代码

调用方接口

/**
* @Author yqq
* @Date 2022/05/28 10:10
* @Version 1.0
*/
@RestController
@RequestMapping("/grab")
public class GrabOrderController {

@Autowired
private RestTemplate restTemplate;
@GetMapping("/do/{goodId}")
public String grabMysql(@PathVariable("goodId") int goodId,int userId){
String url = "http://order-service"+"/grab/do/"+goodId+"?userId="+userId;
restTemplate.getForEntity(url, String.class).getBody();
return "成功";
}
}

Order服务核心代码

/**
* @Author yqq
* @Date 2022/05/28 10:16
* @Version 1.0
*/
@RestController
@RequestMapping("/grab")
public class GrabOrderController {

//无锁
@Autowired
@Qualifier("grabNoLockService")
private GrabService grabService;
@GetMapping("/do/{goodId}")
public String grabMysql(@PathVariable("goodId") int goodId,int userId){
System.out.println("good:"+goodId+",userId:"+userId);
grabService.grabOrder(goodId,userId);
return "";
}
}

grabNoLockService逻辑

/**
* @Author yqq
* @Date 2022/05/28 10:20
* @Version 1.0
*/
@Service("grabNoLockService")
public class GrabNoLockServiceImpl implements GrabService {
@Autowired
private InventoryService inventoryService;
@Override
public String grabOrder(int goodId, int userId) {
System.out.println("用户:"+userId+" 执行抢单逻辑");
boolean flag = inventoryService.grab(goodId,userId);
if (flag)
System.out.println("用户:"+userId+" 抢单成功");
else
System.out.println("用户:"+userId+" 抢单失败");
return null;
}
}

库存和订单逻辑代码

/**
* @Author yqq
* @Date 2022/05/28 10:14
* @Version 1.0
*/
@Service
public class InventoryServiceImpl extends ServiceImpl<InventoryMapper, Inventory> implements InventoryService{
@Autowired
private InventoryMapper mapper;
@Autowired
private OrderMapper orderMapper;
@Override
public boolean grab(int goodId, int userId) {
Inventory inventory = mapper.selectById(goodId);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
int num = inventory.getNum().intValue();
System.out.println("num:"+num);
if (num > 0){
//扣减库存
inventory.setNum(num-1);
mapper.updateById(inventory);
//新增订单
Order order = new Order();
order.setUserId(userId);
order.setOrderStatus(1);
order.setOrderDesc("用户:"+userId+"抢到了iPhoneSE");
orderMapper.insert(order);
return true;
}
return false;
}
}

工具压测

微服务单体服务-抢购/秒杀超卖现象_微服务_03
微服务单体服务-抢购/秒杀超卖现象_微服务_04
微服务单体服务-抢购/秒杀超卖现象_ide_05

抢购后数据

10个线程执行完毕

微服务单体服务-抢购/秒杀超卖现象_mysql_06

库存表

库存扣减失败
微服务单体服务-抢购/秒杀超卖现象_ide_07

订单表

订单表从库存表中抢购2个商品,结果10个线程都抢到了。。。。。。。so。。。。。。
微服务单体服务-抢购/秒杀超卖现象_ide_08
肯定不能这么干,超卖了,超卖了,我想加把锁。。。。。。