@Transactional(rollbackFor = Exception.class) - Spring事务中如何使用RocketMQ消息保证库存一致性
@Transactional(rollbackFor = Exception.class) TackAnOrderVo tackAnOrder(@RequestBody @Validated PlaceOrderVo vo){
//提交订单
//提交库存
/提交其它
// 发送消息到 MQ TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter(){ @Override public void afterCommit() { //发送mq更新es库存标志 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)); drugChangeMessage.setUpdatedQuantity(// 获取扣减后的库存数量); drugProducer.sendDrugChangeMsg(drugChangeMessage); }
}
});
} rocketmq消息在其它服务消费,查询库存还是扣减前的库存数量,怎么改代码,消费是查询库存时是变更后的库存内容:To ensure that the consumed messages reflect the updated inventory quantity, you need to modify the code in the consumer service. Currently, the consumer is querying the inventory before the deduction. To query the inventory after the deduction, you can make the following changes:
-
Modify the message structure to include the updated inventory quantity after the deduction. You can add a new field, such as 'updatedQuantity', to the 'DrugChangeMessage' class.
-
In the producer service, when sending the 'DrugChangeMessage' to the MQ, set the 'updatedQuantity' field to the new inventory quantity after the deduction.
-
In the consumer service, when consuming the 'DrugChangeMessage', retrieve the 'updatedQuantity' field from the message and use it for inventory queries instead of the previous quantity.
Here's an example of how you can modify the consumer service code:
// Import necessary packages
@Service
public class InventoryService {
// Inject necessary dependencies
@RocketMQMessageListener(topic = 'inventory-topic', consumerGroup = 'inventory-consumer-group')
public class InventoryMessageListener implements RocketMQListener<DrugChangeMessage> {
@Override
public void onMessage(DrugChangeMessage message) {
// Retrieve the updated quantity from the message
int updatedQuantity = message.getUpdatedQuantity();
// Use the updated quantity for inventory queries
// ...
}
}
}
By modifying the message structure and updating the consumer service to retrieve the updated quantity, you can ensure that the consumed messages reflect the changes made to the inventory.
原文地址: https://www.cveoy.top/t/topic/pgK4 著作权归作者所有。请勿转载和采集!