Spring Boot + Vue 3 异步任务与线程池:@Async 生效条件与任务丢失
Spring Boot + Vue 3 异步任务与线程池:@Async 生效条件与任务丢失
一个导出接口加了 @Async,本地点一下返回很快,上线后偶尔发现任务没跑完、异常在日志里只剩一行、重启 pod 时又丢了一批。这些现象大多不是并发写错了,而是没搞清楚三件事:注解到底由哪个代理执行、任务提交给了哪个执行器、以及上下文和异常在哪一层被丢掉。这一篇按 Spring Framework 与 Spring Boot 参考文档、以及相关 javadoc,把这条链路逐段拆开。
一、@Async 做了什么,又没做什么
Spring Framework 参考文档的原话是:"the caller returns immediately upon invocation, while the actual execution of the method occurs in a task that has been submitted to a Spring TaskExecutor."
这句话有两层含义。调用方拿到的只是"任务已提交",不是"任务已完成";方法体里的异常、事务、返回值都不在原来的调用栈上了。
同步调用:
请求线程 ──▶ service.doWork() ──▶ 业务逻辑 ──▶ 返回/抛异常 ──▶ 响应
异步调用:
请求线程 ──▶ 代理 ──▶ 提交任务到 TaskExecutor ──▶ 立即返回
│
└─ 工作线程 ──▶ 业务逻辑 ──▶ 异常/结果另走一路
| 关注点 | 同步 | @Async |
|---|---|---|
| 返回值 | 直接拿到结果 | void 或 Future 类型;调用方立即返回 |
| 异常 | 沿调用栈抛给上层 | Future.get() 时抛出,或 void 时交给 AsyncUncaughtExceptionHandler |
| 事务 | 与外层同一调用链 | 异步方法内是自己的执行上下文,外层事务不会延伸过来 |
| 线程上下文 | 请求线程上的一切 | 默认不带过去(MDC、安全上下文等) |
| 失败感知 | 接口直接报错 | 接口已经返回成功,用户以为完成了 |
最后一行是异步化最容易低估的代价:HTTP 200 发出去之后,任务失败用户是不知道的。所以凡是有业务结果的异步操作,都得另有查询或通知机制,光加一个注解等于把失败藏起来。
二、生效条件:开关、代理、返回类型
开关。 官方文档要求把 @EnableAsync 加在某个 @Configuration 类上,或用 <task:annotation-driven> 元素。和缓存、事务一样,注解本身不触发行为。
代理模式与自调用。 参考文档原文:
The default advice mode for processing
@Asyncannotations isproxywhich allows for interception of calls through the proxy only. Local calls within the same class cannot get intercepted that way. For a more advanced mode of interception, consider switching toaspectjmode in combination with compile-time or load-time weaving.
@Service
public class ReportService {
public void export(ReportCmd cmd) {
prepare(cmd); // 应用自定义的准备工作
doExport(cmd); // 同类内部调用,不经过代理,@Async 不生效
}
@Async
public void doExport(ReportCmd cmd) {
// 期望异步执行,实际还在原请求线程里跑
}
}
这类代码不会报错,接口只是变慢,测试环境数据量小甚至看不出来。要拆到另一个 bean,或者改用 AspectJ 织入。
返回类型。 文档说得很明确:void 可以;带返回值的方法"are required to have a Future-typed return value";此外 @Async 方法还可以声明 java.util.concurrent.CompletableFuture,"for richer interaction with the asynchronous task and for immediate composition with further processing steps"。也就是说返回一个普通对象不是"异步但拿不到值",而是不符合契约的写法。
void 方法的异常会被吞。 这是全篇最该记住的一条:
When an
@Asyncmethod has aFuture-typed return value, it is easy to manage an exception ... With avoidreturn type, however, the exception is uncaught and cannot be transmitted. You can provide anAsyncUncaughtExceptionHandlerto handle such exceptions. ... By default, the exception is merely logged.
默认只打一行日志,不会触发全局异常处理器,也不会通知任何人。业务上要感知失败,就得自己实现:
@Component
public class ReportAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(ReportAsyncExceptionHandler.class);
private final TaskFailureRecorder taskFailureRecorder; // 应用自定义组件
public ReportAsyncExceptionHandler(TaskFailureRecorder taskFailureRecorder) {
this.taskFailureRecorder = taskFailureRecorder;
}
/** 处理 void 异步方法中无法回传的异常,记录失败状态供后续查询 */
@Override
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
// params 里能拿到方法入参,可据此定位到具体任务并更新失败状态
log.error("异步任务失败: {}#{}", method.getDeclaringClass().getSimpleName(),
method.getName(), ex);
taskFailureRecorder.markFailed(method, params, ex);
}
}
通过 AsyncConfigurer 或 <task:annotation-driven/> 把它注册进去。更稳的做法是干脆别用 void:返回 CompletableFuture 后,异常会随 future 传播,调用方 exceptionally(...) 就能处理。
| 返回类型 | 异常去哪了 | 建议 |
|---|---|---|
void |
AsyncUncaughtExceptionHandler,默认仅日志 |
关键任务避免用,或注册自定义 handler |
Future<T> |
调用 get() 时抛出 |
注意别在请求线程里立刻 get(),那就白异步了 |
CompletableFuture<T> |
随 future 传播,可组合处理 | 需要失败感知时的首选 |
三、默认执行器不是你以为的那个
这里有两套完全不同的默认值,混淆它们会得出错误结论。
Spring Framework 原生实现类。 参考文档的 TaskExecutor 类型清单里:
SimpleAsyncTaskExecutor: This implementation does not reuse any threads. Rather, it starts up a new thread for each invocation. ... If you are looking for true pooling, seeThreadPoolTaskExecutor, later in this list.
ThreadPoolTaskExecutor: This implementation is most commonly used. It exposes bean properties for configuring ajava.util.concurrent.ThreadPoolExecutor... It also provides a pause/resume capability and graceful shutdown through Spring's lifecycle management.
而 ThreadPoolTaskExecutor 的 javadoc 默认值更值得注意:
| 方法 | 默认值 | 含义 |
|---|---|---|
setCorePoolSize |
1 | 核心线程数 |
setMaxPoolSize |
Integer.MAX_VALUE |
最大线程数 |
setQueueCapacity |
Integer.MAX_VALUE |
正数用 LinkedBlockingQueue,其他值用 SynchronousQueue |
自己 new ThreadPoolTaskExecutor() 而不设参数,得到的是"1 个核心线程 + 近乎无界队列",maxPoolSize 基本永远用不上。
Spring Boot 自动配置。 Boot 参考文档:
In the absence of an
Executorbean in the context, Spring Boot auto-configures anAsyncTaskExecutor. When virtual threads are enabled (using Java 21+ andspring.threads.virtual.enabledset totrue) this will be aSimpleAsyncTaskExecutorthat uses virtual threads. Otherwise, it will be aThreadPoolTaskExecutorwith sensible defaults.
自动配置的 ThreadPoolTaskExecutor "uses 8 core threads that can grow and shrink according to the load"。也就是说 Boot 的默认值是 8 核,和原生 javadoc 的 1 核不是一回事。
最容易踩的坑是自动配置退让。 文档原文:
By default, when a custom
Executorbean is registered, the auto-configuredAsyncTaskExecutorbacks off, and the customExecutoris used for regular task execution (via@EnableAsync).
项目里为了某个定时任务随手加了一个 Executor bean,整个应用所有 @Async 的执行器就换成了它,线程池大小、拒绝策略、监控指标全都跟着变。Boot 给了两个补救手段:自定义 bean 上标 @Bean(defaultCandidate = false) 让它参与注入但不影响自动配置;或者设 spring.task.execution.mode=force,此时 "The auto-configured AsyncTaskExecutor will be used automatically for all integrations, even if a custom Executor bean is registered, including those marked as @Primary",唯一能覆盖常规任务执行器的只剩 AsyncConfigurer bean。
容器里有 Executor bean 吗?
├─ 没有 → Boot 自动配置 AsyncTaskExecutor
│ ├─ spring.threads.virtual.enabled=true → SimpleAsyncTaskExecutor(虚拟线程)
│ └─ 否则 → ThreadPoolTaskExecutor(8 核起步)
├─ 有,默认行为 → 自动配置退让,自定义 Executor 接管 @EnableAsync
├─ 有,但标了 @Bean(defaultCandidate=false) → 保留自动配置
└─ 有,且 spring.task.execution.mode=force → 强制用自动配置的
Boot 还列出了这个执行器会被哪些集成共用:@EnableAsync 的异步任务、Spring MVC 的异步请求处理、WebFlux 的阻塞执行支持、WebSocket 入站出站通道、GraphQL 的 Callable、JPA bootstrap、以及 ApplicationContext 后台初始化。也就是说改一个 spring.task.execution.pool.*,影响的不只是 @Async。
四、线程池参数与队列的真实行为
Boot 文档给的调参示例:
spring.task.execution.pool.max-size=16
spring.task.execution.pool.queue-capacity=100
spring.task.execution.pool.keep-alive=10s
文档对这组配置的解释很关键:"This changes the thread pool to use a bounded queue so that when the queue is full (100 tasks), the thread pool increases to maximum 16 threads. Shrinking of the pool is more aggressive as threads are reclaimed when they are idle for 10 seconds (rather than 60 seconds by default)."
把这段话拆开,能得到两条常被误用的结论:
| 误解 | 文档给出的实际行为 |
|---|---|
设了 max-size=16,并发一上来就会扩到 16 |
队列先填满(100),之后才扩容到最大线程数 |
keep-alive 控制任务执行超时 |
它控制的是空闲线程多久被回收,默认 60 秒,和任务耗时无关 |
| 队列越大越安全 | 无界队列会让扩容几乎不发生,请求只是排队,延迟持续升高且不易察觉 |
最后一条和前一篇讲接口超时时是同一个道理:队列里等着的任务对调用方不可见。任务提交成功不代表会被及时处理,队列积压要靠 activeCount、poolSize、队列长度这些指标看,javadoc 也提到 ThreadPoolTaskExecutor "is also well suited for management and monitoring (for example, through JMX)",这些属性支持运行时读取甚至修改。
拒绝策略方面,ThreadPoolTaskExecutor 的 javadoc 方法清单里有 setRejectedExecutionHandler;任务被拒绝时怎么反馈给调用方,需要结合业务决定,不能只依赖默认行为把异常吞在提交环节。
五、指定执行器与多个执行器
默认执行器之外的任务可以用 @Async 的 value 指定:
@Async("reportExecutor")
public CompletableFuture<Report> buildReport(ReportCmd cmd) {
return CompletableFuture.completedFuture(render(cmd));
}
参考文档说明,这个值"can be the name of any Executor bean in the Spring container, or it may be the name of a qualifier associated with any Executor"——bean 名或 @Qualifier 指定的限定符都行。默认执行器则来自启用异步支持时配置的那一个,也就是 AsyncConfigurer 实现或 XML 的 annotation-driven 元素。
Boot 文档还给了一个"一套业务执行器 + 一套 MVC/WebFlux 执行器"的写法:注册名为 applicationTaskExecutor 的 bean 供各集成共用,另注册名为 taskExecutor 的 bean 供 @EnableAsync 常规任务使用。文档同时提醒,applicationTaskExecutor 在"没有 @Primary bean、也没有名为 taskExecutor 的 Executor 或 AsyncConfigurer"时也会用于常规任务执行。命名规则比看起来复杂,改之前最好先把容器里实际的 Executor bean 列一遍。
六、上下文和异常不会自动跟过去
异步切换线程后,请求线程上的东西不会自动出现在工作线程上。Spring Boot 参考文档 "Observability" 章节给了明确结论:
If you're working with
@Asyncmethods and theAsyncTaskExecutoris auto-configured, you have to opt-in for context propagation using thespring.task.execution.propagate-contextproperty.
自己配置执行器时,则要注册 ContextPropagatingTaskDecorator bean。响应式侧对应 spring.reactor.context-propagation=auto,因为 "By default, ThreadLocal values are not automatically reinstated in reactive operators"。这几条在链路追踪那篇里展开过,这里只强调一点:MDC 丢失不是日志框架的问题,是执行器没开传播。
TaskDecorator 的 javadoc 还有两个提示:它的主要用途是 "to set some execution context around the task's invocation, or to provide some monitoring/statistics";装饰的对象"is not necessarily being applied to the user-supplied Runnable/Callable but rather to the actual execution callback"。另外 submit 调用下暴露的是 FutureTask,"does not propagate any exceptions",想在装饰器里统计异常得另想办法。
还有一条组合语义值得记:参考文档说 @Async 与 @Retryable 一起用时,"the async advice is applied outermost, so all retry attempts run on the async executor thread"。也就是整串重试都占用同一个异步线程,重试期间不会回到请求线程。
| 需要跨线程的东西 | 默认是否跟过去 | 处理方式 |
|---|---|---|
MDC 的 traceId / spanId |
否 | spring.task.execution.propagate-context 或 ContextPropagatingTaskDecorator |
| Spring Security 上下文 | 否 | 专用的委托执行器或显式传递 |
外层 @Transactional 事务 |
否 | 异步方法内的事务是独立的,别指望回滚外层 |
void 方法的异常 |
否 | AsyncUncaughtExceptionHandler 或改返回 CompletableFuture |
请求作用域 bean / RequestContextHolder |
否 | 在提交前把需要的值取出来当参数传 |
最后三行属于工程上的判断,官方文档主要明确的是前两行。共同点是:异步边界一旦跨过去,靠 ThreadLocal 维系的任何东西都要重新考虑。
异步任务别去回查刚写的数据
一个难复现但很典型的坑:外层方法带 @Transactional,先写了一条记录,再调用 @Async 方法去处理它。异步任务一提交就可能在另一个线程跑起来,此时外层事务还没提交,工作线程查数据库读不到那条记录,于是按"数据不存在"处理掉了。
请求线程:BEGIN ──▶ INSERT ──▶ 提交 @Async 任务 ──▶ 继续业务 ──▶ COMMIT
│
工作线程: └─▶ SELECT 那条记录 → 读不到(未提交)
@Async 参考文档没有规定它和 @Transactional 的 advice 顺序,所以别把正确性寄托在谁先谁后上。两种稳妥做法:把需要的数据当参数传进去,不让异步任务回查;或者等提交后再触发——@TransactionalEventListener 默认阶段就是 AFTER_COMMIT,但它的 javadoc 有两条规定要记住:没有活动事务时事件默认被丢弃(要设 fallbackExecution = true),以及 AFTER_COMMIT 里做的数据访问改动 "will not be committed to the transactional resource",所以监听器适合发事件、清缓存,不适合写库。这几条在缓存一致性那篇里核对过。
| 做法 | 适用 | 风险 |
|---|---|---|
| 把数据当参数传入 | 数据不大、结构稳定 | 参数过多时不好维护 |
| 提交后再发事件触发 | 希望业务逻辑与触发点解耦 | 事件默认在无事务时被丢弃 |
| 异步任务里 sleep 等外层提交 | 不推荐 | 等待时间没有依据,且掩盖了顺序问题 |
最后一行是常见的临时修复,本质是把不确定变成更不确定的延迟,别用。
七、优雅停机时任务会怎样
Spring Framework 6.1 之后这块行为有变化,ThreadPoolTaskExecutor 的 javadoc 说得很细:
Specify whether to initiate an early shutdown signal on context close, disposing all idle threads and rejecting further task submissions. ... By default, existing tasks will be allowed to complete within the coordinated lifecycle stop phase in any case. ... As of 6.1.4, the default is "false", leniently allowing for late tasks to arrive after context close, still participating in the lifecycle stop phase.
strictEarlyShutdown 从 6.1.4 起默认 false,意思是上下文关闭时不立刻调用 ThreadPoolExecutor.shutdown(),已有任务在协调的生命周期停止阶段里继续跑完。文档接着提醒:setAcceptTasksAfterContextClose 和 setWaitForTasksToCompleteOnShutdown 这两个标志"will override this setting, leading to a late shutdown without a coordinated lifecycle stop phase"——一旦设了它们,就退回到"延迟关停"那条路径,不再走协调停止阶段。
应用收到 SIGTERM
│
├─ ContextClosedEvent
│ └─ strictEarlyShutdown=false(6.1.4 起默认)
│ └─ 已有任务在协调停止阶段内跑完
│
├─ 若设了 waitForTasksToCompleteOnShutdown
│ └─ 覆盖上述设置 → 延迟关停路径
│
└─ 超过容器 terminationGracePeriodSeconds → 进程被杀,任务中断
Boot 侧还有 spring.task.execution.shutdown.* 对应配置,但它作用于自动配置的执行器;一旦 Executor 是自己注册的那个 bean,这些配置不会生效,得在 bean 上自己调 setWaitForTasksToCompleteOnShutdown(true) / setAwaitTerminationSeconds(...)。这也是为什么"配了优雅停机参数,重启还是丢任务"的常见原因。
更实际的边界是:无论 Java 侧等多久,容器的 terminationGracePeriodSeconds 一到就得退出。长耗时任务不能靠延长优雅停机兜底,应该落库成可恢复的任务记录,重启后接着跑。这一步属于工程方案,Spring 不提供。
八、前端怎么知道异步任务的结果
@Async 之后接口立刻返回,浏览器拿不到最终结果。可落地的方案通常是:提交时返回一个任务 ID,任务状态落库,前端轮询或用 SSE 查(本系列 SSE 篇讲过连接、重连与补发)。
// TaskStatus<T> 为业务自定义的任务状态结构(state / result / error)
/** 轮询异步任务状态,终态后停止;间隔与上限由调用方控制 */
export async function waitForTask<T>(taskId: string,
query: (id: string) => Promise<TaskStatus<T>>,
intervalMs = 1500,
maxAttempts = 40): Promise<TaskStatus<T>> {
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const status = await query(taskId);
if (status.state === 'SUCCESS' || status.state === 'FAILED') {
return status; // 终态:成功或明确失败
}
await new Promise((resolve) => window.setTimeout(resolve, intervalMs));
}
return { state: 'TIMEOUT' } as TaskStatus<T>; // 交给界面提示"结果未知"
}
| 设计点 | 为什么需要 |
|---|---|
| 任务状态落库 | 进程重启后还能查到,纯内存 Map 会丢 |
| 明确的失败态 | void 异步方法的异常默认只进日志,接口永远不会报错 |
| 终态判定 | 避免前端无限轮询;超时后提示结果未知而不是"失败" |
| 幂等的任务 ID | 用户重复点提交时不要生成两份任务 |
这些都是工程约定,不是 Spring 提供的能力。特别是最后一行:异步化之后用户看不到即时反馈,重复点击的概率反而更高,提交接口还是要配幂等键(本系列幂等篇讲过实现)。
任务记录与重启恢复
内存里的 Map<taskId, Future> 进程一停就没了。要撑住重启,任务得有持久状态:
PENDING ──▶ RUNNING ──▶ SUCCESS
│
└─▶ FAILED(记录异常摘要,供前端展示)
重启后:扫描长期停留在 RUNNING 的任务 → 重新入队或标记 FAILED
| 字段 | 用途 |
|---|---|
task_id |
提交接口返回给前端的查询键,同时作为幂等键 |
state |
驱动前端轮询的终态判定 |
params |
重启后重跑所需的输入(注意脱敏) |
error |
失败原因摘要,对应 AsyncUncaughtExceptionHandler 捕获到的异常 |
updated_at |
判断 RUNNING 是否已超时、是否需要重新入队 |
这套表结构属于工程实现,Spring 不提供。它的价值正落在第七节说的边界上:优雅停机等不到、容器宽限期到了、pod 被直接杀掉,只要状态落了库,就有得查也有得恢复。
九、排查清单
| 现象 | 优先检查 | 验证方式 |
|---|---|---|
@Async 完全没异步 |
没加 @EnableAsync;同类自调用 |
在方法里打印线程名,与请求线程比对 |
| 任务失败但接口返回成功 | void 返回类型,异常仅被记录 |
查 AsyncUncaughtExceptionHandler 是否注册、日志里有无异常 |
| 断言拿到的是结果对象 | 返回类型不是 Future |
改成 CompletableFuture<T> |
| 线程池行为和配置对不上 | 自定义 Executor bean 导致自动配置退让 |
列出容器里所有 Executor bean 及其类型 |
| 并发上不去、线程数始终很小 | 无界队列,max-size 不生效 |
看队列长度与 poolSize,改有界 queue-capacity |
| 异步日志没有 traceId | 未开上下文传播 | spring.task.execution.propagate-context 或注册 decorator |
| 重启丢任务 | 停机等待时间、任务是否可恢复 | 比对 terminationGracePeriodSeconds 与任务耗时;检查任务是否落库 |
| 重试期间线程一直被占 | @Async + @Retryable 的 advice 顺序 |
官方说明所有重试都在异步执行线程上 |
| 前端一直转圈 | 没有终态或超时判定 | 检查轮询封装与失败态写入 |
十、收口
把 @Async 用对,需要同时回答四个问题:注解有没有被代理拦到、任务交给了哪个执行器、失败与上下文怎么跨过线程边界、应用关闭时这批任务怎么办。这四问对应的分别是 @EnableAsync 与自调用、Executor bean 与自动配置退让、Future 返回类型与上下文传播、优雅停机与可恢复任务记录。少了哪一环,表现都是"接口很快返回,然后什么也没发生"——而这类问题在本地小数据量下几乎不会暴露。