在进行秒杀项目的开发过程中,遇到了一个问题,下单-库存减少
异步处理库存,下单后,进行redis操作,订单入库,销量增加,异步操作数据库库存
一、直接使用Springboot提供方法
// Springboot 提供的事务操作方法 当前事务操作成功 方法调用
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
// 异步更新库存
boolean mqResult = itemService.asyncDecreaseStock(itemId, amount);
if (!mqResult) {
itemService.increaseStock(itemId, amount);
throw new BusinessException(EmBusinessError.MQ_SEND_FAIL);
}
}
});
二、通过库存流水进行状态标识,配合rocketmq事务
- RocketMQ TransactionMQProducer 设置listener
- executeLocalTransaction 进行事务方法的处理
- checkLocalTransaction 进行异常事务的处理
具体的操作逻辑
1、controller 进行 mq异步事务调用
if (redisTemplate.hasKey("promo_stock_invalid_" + itemId)) {
throw new BusinessException(EmBusinessError.STOCK_NOT_ENOUGH);
}
// 加入库存流水
String stockLogResultId = itemService.initStockLog(itemId, amount);
// 完成下单事务消息
if (!mqProducer.transactionAsyncReduceStock(userModel.getId(), itemId, promoId, amount, stockLogResultId)) {
throw new BusinessExcep