使用Spring Batch多线程读取CSV文件并对MongoDB执行更新/upsert操作
Spring Boot MongoDB CSV批量Upsert性能优化方案
核心优化方向
- 用MongoDB原生批量操作替代单条循环写入
- 多线程分片处理CSV数据,结合流式读取避免OOM
- 提前优化MongoDB索引及连接池配置
具体实现示例
1. 基础依赖配置
除了spring-boot-starter-data-mongodb外,推荐用OpenCSV做流式CSV读取,依赖如下:
<!-- OpenCSV 流式读取CSV --> <dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>5.6</version> </dependency>
2. 自定义线程池配置
Spring Boot中配置专用的批量处理线程池,注意核心线程数不要超过MongoDB连接池的最大连接数(默认值为100,建议线程数设置为10~30即可,可根据实际压测调整):
@Configuration public class ThreadPoolConfig { @Bean("csvProcessPool") public Executor csvProcessPool() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(16); executor.setMaxPoolSize(32); executor.setQueueCapacity(100); executor.setThreadNamePrefix("csv-process-"); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } }
3. 批量Upsert核心逻辑
用MongoTemplate的bulkOps实现批量upsert,单批次建议控制在1000~5000条:
@Service public class CsvMongoService { @Resource private MongoTemplate mongoTemplate; @Resource(name = "csvProcessPool") private Executor csvProcessPool; // 每批次处理条数,可根据单条数据大小调整 private static final int BATCH_SIZE = 2000; public void processCsv(InputStream inputStream) throws Exception { // 流式读取CSV,避免全量加载到内存 CsvToBean<YourDataEntity> csvToBean = new CsvToBeanBuilder<YourDataEntity>(new InputStreamReader(inputStream, StandardCharsets.UTF_8)) .withType(YourDataEntity.class) .withIgnoreLeadingWhiteSpace(true) .build(); Iterator<YourDataEntity> iterator = csvToBean.iterator(); List<YourDataEntity> batchList = new ArrayList<>(BATCH_SIZE); List<CompletableFuture<Void>> futures = new ArrayList<>(); while (iterator.hasNext()) { batchList.add(iterator.next()); // 凑够一批就提交异步处理 if (batchList.size() >= BATCH_SIZE) { List<YourDataEntity> currentBatch = new ArrayList<>(batchList); // 提交线程池处理 CompletableFuture<Void> future = CompletableFuture.runAsync(() -> batchUpsert(currentBatch), csvProcessPool); futures.add(future); batchList.clear(); } } // 处理最后不足一批的数据 if (!batchList.isEmpty()) { CompletableFuture<Void> future = CompletableFuture.runAsync(() -> batchUpsert(batchList), csvProcessPool); futures.add(future); } // 等待所有批次处理完成 CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); } private void batchUpsert(List<YourDataEntity> batchList) { // BulkMode选择UNORDERED时,MongoDB会并行执行该批次内的写入请求,性能更高;如果批次内数据有顺序依赖,可替换为ORDERED BulkOperations bulkOps = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, YourDataEntity.class); for (YourDataEntity entity : batchList) { // 构造查询条件,按你的业务唯一键来,比如userId、orderId之类 Query query = new Query(Criteria.where("uniqueKey").is(entity.getUniqueKey())); // 构造更新内容,注意:Update.fromEntity方法需要Spring Data MongoDB 3.0及以上版本,低版本可以手动遍历实体字段构造Update对象 Update update = Update.fromEntity(entity); // 配置为upsert模式 bulkOps.upsert(query, update); } // 执行批量操作 bulkOps.execute(); } }
额外优化建议
- 给upsert的查询字段加唯一索引,可以大幅提升查询匹配速度,同时避免重复数据
- 调整MongoDB连接池配置,在application.yml中增加配置:
spring: data: mongodb: uri: mongodb://xxx:xxx@host:port/db connection-pool: max-size: 100 min-size: 10 max-connection-life-time: 30000 max-connection-idle-time: 10000
- 如果CSV文件超过1G,可以提前把大文件拆分为多个小文件,再并行处理,避免单线程读取大文件成为瓶颈
- 压测调整批次大小和线程数,不同数据大小的最优参数不同,建议以实际压测的TPS为准
内容的提问来源于stack exchange,提问作者user1748379
相关产品推荐
相关产品推荐

