典型用法
基本使用:启用异步方法
在配置类上添加 @EnableAsync,即可启用对 @Async 注解的支持,然后在服务类中定义异步方法。
@Configuration
@EnableAsync
public class AsyncConfig {
}
@Service
public class MyService {
@Async
public void asyncMethod() {
System.out.println("当前线程: " + Thread.currentThread().getName());
// 模拟耗时操作
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("异步方法执行完成");
}
}
指定自定义线程池
默认情况下,Spring 使用 SimpleAsyncTaskExecutor,不复用线程。推荐自定义线程池以提升性能和资源管理能力。
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurerSupport {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5); // 核心线程数
executor.setMaxPoolSize(10); // 最大线程数
executor.setQueueCapacity(100); // 队列容量
executor.setThreadNamePrefix("Async-"); // 线程名前缀
executor.setWaitForTasksToCompleteOnShutdown(true); // 关闭时等待任务完成
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (ex, method, params) -> {
System.err.println("异步方法异常: " + ex.getMessage());
ex.printStackTrace();
};
}
}
结合 @Profile 控制环境启用
@Configuration
@EnableAsync
@Profile("prod")
public class ProdAsyncConfig {
}
AOP 增强异步方法
可以通过 AOP 对异步方法进行日志记录、监控等增强操作:
@Aspect
@Component
public class AsyncAspect {
@Before("@annotation(org.springframework.scheduling.annotation.Async)")
public void beforeAsyncMethod(JoinPoint joinPoint) {
System.out.println("即将执行异步方法: " + joinPoint.getSignature().getName());
}
@AfterReturning("@annotation(org.springframework.scheduling.annotation.Async)")
public void afterAsyncMethod(JoinPoint joinPoint) {
System.out.println("异步方法执行完成: " + joinPoint.getSignature().getName());
}
}
Spring Boot 中的典型应用
@SpringBootApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}