关注博主,索要git仓库完整源码
抢购前数据
库存表
订单表
核心代码
调用方接口
/**
* @Author yqq
* @Date 2022/05/28 10:10
* @Version 1.0
*/
("/grab")
public class GrabOrderController {
private RestTemplate restTemplate;
("/do/{goodId}")
public String grabMysql( ("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
*/
("/grab")
public class GrabOrderController {
//无锁
("grabNoLockService")
private GrabService grabService;
("/do/{goodId}")
public String grabMysql( ("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
*/
("grabNoLockService")
public class GrabNoLockServiceImpl implements GrabService {
private InventoryService inventoryService;
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
*/
public class InventoryServiceImpl extends ServiceImpl<InventoryMapper, Inventory> implements InventoryService{
private InventoryMapper mapper;
private OrderMapper orderMapper;
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;
}
}
工具压测
抢购后数据
10个线程执行完毕
库存表
库存扣减失败
订单表
订单表从库存表中抢购2个商品,结果10个线程都抢到了。。。。。。。so。。。。。。
肯定不能这么干,超卖了,超卖了,我想加把锁。。。。。。