-- 库存表拆分
ALTER TABLE inventory ADD COLUMN sub_stock_1 INT DEFAULT 0;
ALTER TABLE inventory ADD COLUMN sub_stock_2 INT DEFAULT 0;
CREATE INDEX idx_product_sub ON inventory(product_id, sub_index);
public interface InventoryMapper {@Update("UPDATE inventory SET sub_stock_#{subIndex} = sub_stock_#{subIndex} - #{count} " +"WHERE product_id = #{productId} AND sub_stock_#{subIndex} >= #{count}")int reduceSubStock(@Param("productId") String productId, @Param("count") int count,@Param("subIndex") int subIndex);
}
二、高并发优化方案
1. 异步提交事务
@Service
public class AsyncOrderService {@Async("seataAsyncExecutor")@GlobalTransactionalpublic CompletableFuture<Void> asyncCreateOrder(OrderDTO order) {inventoryMapper.reduceStock(order.getProductId(), order.getCount());orderMapper.insert(order);return CompletableFuture.completedFuture(null);}
}
2. 批量操作优化
public interface InventoryMapper {@Update({"<script>","UPDATE inventory SET stock = stock - #{count}","WHERE product_id IN","<foreach item='item' collection='productIds' open='(' separator=',' close=')'>","#{item}","</foreach>","</script>"})int batchReduceStock(@Param("productIds") List<String> productIds, @Param("count") int count);
}