@Transactional(rollbackFor = Exception.class) - 确保库存更新与订单提交一致性
@Transactional(rollbackFor = Exception.class) TackAnOrderVo tackAnOrder(@RequestBody @Validated PlaceOrderVo vo){
//提交订单
//提交库存 // Update inventory here
/提交其它
// 发送消息到 MQ within the same transaction TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter(){ @Override public void afterCommit() { //发送mq更新es库存标志
// Query inventory here (Updated inventory after deduction)
for (Long drugId : drugIdList) {
DrugChangeMessage drugChangeMessage = new DrugChangeMessage();
drugChangeMessage.setDrugId(drugId);
drugChangeMessage.setStoreId(order.getStoreId());
drugChangeMessage.setChangeType(5);
drugChangeMessage.setMerchantId(Long.parseLong(merchantId));
drugChangeMessage.setEnterpriseId(Long.parseLong(enterpriseId));
drugChangeMessage.setPlatformId(Long.parseLong(platformId));
drugProducer.sendDrugChangeMsg(drugChangeMessage);
}
}
});
// Return TackAnOrderVo }
通过在同一个事务中更新库存,消费消息的其他服务将能够在扣减后查询更新后的库存。
原文地址: https://www.cveoy.top/t/topic/pgLh 著作权归作者所有。请勿转载和采集!