Spring Boot 集成自定义线程池和异常处理1.Spring Boot 集成自定义线程池一、配置自定义线程池二、使用 Async 实现声明式异步三、Controller 中编排异步结果四、关键注意事项2.Spring Boot 异步全局异常处理一、自定义异常处理器二、注册到 Spring 容器三、CompletableFuture 的异常处理四、核心区别总结1.Spring Boot 集成自定义线程池在 Spring Boot 中通过Configuration配置 Bean并结合Async注解或手动注入ThreadPoolTaskExecutor可实现声明式异步调用。一、配置自定义线程池创建配置类定义ThreadPoolTaskExecutorBean确保参数可控且线程命名规范。importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;importjava.util.concurrent.ThreadPoolExecutor;ConfigurationpublicclassAsyncConfig{Bean(bizTaskExecutor)publicThreadPoolTaskExecutortaskExecutor(){ThreadPoolTaskExecutorexecutornewThreadPoolTaskExecutor();executor.setCorePoolSize(5);executor.setMaxPoolSize(10);executor.setQueueCapacity(100);executor.setKeepAliveSeconds(60);executor.setThreadNamePrefix(biz-async-);// 拒绝策略由调用线程执行起到背压作用executor.setRejectedExecutionHandler(newThreadPoolExecutor.CallerRunsPolicy());executor.initialize();returnexecutor;}}二、使用 Async 实现声明式异步在 Service 层方法上添加Async(bizTaskExecutor)指定使用上述自定义线程池。注意启动类需添加EnableAsync。异步方法必须在另一个类中调用自调用无效因为 Spring AOP 基于代理。importorg.springframework.scheduling.annotation.Async;importorg.springframework.stereotype.Service;importjava.util.concurrent.CompletableFuture;ServicepublicclassOrderService{Async(bizTaskExecutor)publicCompletableFutureStringqueryUserAsync(){try{Thread.sleep(1000);}catch(InterruptedExceptione){}returnCompletableFuture.completedFuture(User_1001);}Async(bizTaskExecutor)publicCompletableFutureStringqueryOrderAsync(){try{Thread.sleep(1200);}catch(InterruptedExceptione){}returnCompletableFuture.completedFuture(Order_List);}}三、Controller 中编排异步结果在 Controller 中注入 Service利用CompletableFuture组合多个异步任务的结果。importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RestController;importjava.util.concurrent.CompletableFuture;RestControllerpublicclassOrderController{AutowiredprivateOrderServiceorderService;GetMapping(/order/detail)publicStringgetOrderDetail()throwsException{// 并行发起两个异步请求CompletableFutureStringuserFutureorderService.queryUserAsync();CompletableFutureStringorderFutureorderService.queryOrderAsync();// 等待所有任务完成并合并结果CompletableFuture.allOf(userFuture,orderFuture).join();return用户: userFuture.get(), 订单: orderFuture.get();}}四、关键注意事项返回值类型Async方法若需返回结果必须返回CompletableFutureT或FutureT否则调用方无法获取返回值。异常处理异步方法中的异常不会直接抛出到 Controller。建议配置全局AsyncUncaughtExceptionHandler或在CompletableFuture链中处理。事务问题Async方法默认不在主事务中运行。若需事务需在异步方法内部单独开启Transactional。2.Spring Boot 异步全局异常处理在 Spring Boot 中Async方法的异常无法被 Controller 的ExceptionHandler捕获。需配置AsyncUncaughtExceptionHandler进行统一兜底防止异常静默丢失。一、自定义异常处理器实现AsyncUncaughtExceptionHandler接口记录日志或发送告警。importorg.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;importlombok.extern.slf4j.Slf4j;importjava.lang.reflect.Method;Slf4jpublicclassCustomAsyncExceptionHandlerimplementsAsyncUncaughtExceptionHandler{OverridepublicvoidhandleUncaughtException(Throwableex,Methodmethod,Object...params){log.error(异步任务异常 - 方法: {}, 参数: {},method.getName(),params,ex);// 此处可集成监控告警如 Sentry/Prometheus}}二、注册到 Spring 容器在配置类中重写getAsyncExecutor和getAsyncUncaughtExceptionHandler方法。importorg.springframework.context.annotation.Configuration;importorg.springframework.scheduling.annotation.AsyncConfigurer;importorg.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;importjava.util.concurrent.Executor;ConfigurationpublicclassAsyncConfigimplementsAsyncConfigurer{OverridepublicExecutorgetAsyncExecutor(){ThreadPoolTaskExecutorexecutornewThreadPoolTaskExecutor();executor.setCorePoolSize(5);executor.setMaxPoolSize(10);executor.setQueueCapacity(100);executor.setThreadNamePrefix(biz-async-);executor.initialize();returnexecutor;}OverridepublicAsyncUncaughtExceptionHandlergetAsyncUncaughtExceptionHandler(){returnnewCustomAsyncExceptionHandler();}}三、CompletableFuture 的异常处理若使用CompletableFuture需在链式调用末尾添加exceptionally或handle确保业务级异常被捕获。future.thenApply(res-process(res)).exceptionally(ex-{log.error(业务处理失败,ex);returndefaultResult;// 返回默认值防止链路中断});四、核心区别总结场景异常捕获方式适用情况Async 无返回值AsyncUncaughtExceptionHandler简单通知、日志记录等“发了就不管”的场景。CompletableFuture.exceptionally()/.handle()需要获取结果、进行业务补偿或降级的场景。Controller 层RestControllerAdvice无效。无法捕获异步线程抛出的异常。