Spring @EnableAsync 典型用法

典型用法

基本使用:启用异步方法

在配置类上添加 @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);
    }
}
解释代码及其作用:@Primary @Configuration @EnableAsync @Slf4j public class ThreadPoolConfig { @ConfigurationProperties("executor-pool.ams") public ExecutorProperties amsExecutorProperties() { return new ExecutorProperties(); } @Bean("amsAsyncExecutor") @Primary public ThreadPoolTaskExecutor amsAsyncExecutor() { return initThreadPoolCommon("amsAsync-", amsExecutorProperties()); } @Bean(name = "amsAsyncExecutorServiceMetrics") public ExecutorServiceMetrics amsAsyncExecutorServiceMetrics() { ThreadPoolTaskExecutor executor = amsAsyncExecutor(); return new ExecutorServiceMetrics(executor.getThreadPoolExecutor(), "amsAsyncExecutor", Collections.emptySet()); } private ThreadPoolTaskExecutor initThreadPoolCommon( String threadNamePrefix, ExecutorProperties executorProperties) { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 核心线程数 executor.setCorePoolSize(executorProperties.getCorePoolSize()); // 最大线程数 executor.setMaxPoolSize(executorProperties.getMaxPoolSize()); // 队列大小 executor.setQueueCapacity(executorProperties.getQueueCapacity()); // 线程池维护线程所允许的空闲时间 executor.setKeepAliveSeconds(executorProperties.getKeepAliveSeconds()); // core线程过期也需要销毁 executor.setAllowCoreThreadTimeOut(true); // reject策略(用于被拒绝任务的处理程序,它直接在execute方法的调用线程中运行被拒绝的任务) executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy()); // 线程池名前缀 executor.setThreadNamePrefix(threadNamePrefix); // 优雅停机,等所有任务执行完才停止线程池 executor.setWaitForTasksToCompleteOnShutdown(true); // 初始化 executor.initialize(); return executor; } }
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值