You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot异步处理Excel:用CompletableFuture收集失败记录

解决方案

1. 在控制器中处理异步任务的完成回调

你已经通过importService.processExcelFile(worksheet)获取到了CompletableFuture<List<String>>,只需为这个Future添加完成回调,就能在异步任务结束后拿到合并后的错误列表,进而触发邮件发送逻辑:

CompletableFuture<List<String>> completableFutureErrorsList = importService.processExcelFile(worksheet);

// 添加异步完成回调
completableFutureErrorsList.whenComplete((errorsList, exception) -> {
    if (exception != null) {
        // 处理异步任务执行过程中出现的全局异常
        logger.error("Excel文件处理任务执行异常", exception);
        return;
    }
    
    // 错误列表非空时,调用邮件服务发送
    if (!errorsList.isEmpty()) {
        // 替换为你的邮件发送逻辑
        emailService.sendImportErrorEmail(errorsList);
    }
});

2. 修正服务层无效代码

你的processExcelRow方法中,CompletableFuture.failedFuture(new Exception("Missing Name"));这行代码是无效的——它创建了一个失败的Future但没有被任何逻辑处理,完全可以删除,因为你已经将错误信息添加到了errorsList中,后续会通过返回的Future统一获取。修正后的方法:

public void processExcelRow(XSSFRow row, List<String> errorsList) {
    XSSFCell cell = row.getCell(0, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
    if (cell == null) {
        errorsList.add("Missing Name");
        // 移除无效的failedFuture调用
    } else {
        // 正常行处理逻辑
    }
}

3. 确保异步配置正确

确认你的Spring Boot项目已经开启异步支持:

  • 在启动类上添加@EnableAsync注解
  • importService类被Spring容器管理(比如添加@Service注解)

这样就能保证异步任务正常执行,并且在任务结束后自动触发错误列表的邮件发送流程。


内容的提问来源于stack exchange,提问作者user3919727

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 02:12:13