springboot中@Async多线程注解使用

本文介绍了SpringBoot中使用@Async注解简化多线程编程的方法。首先,通过创建线程池配置类来管理多线程。然后,通过在方法上添加@Async注解,使其在调用时由线程池异步执行。测试调用显示了这种实现的简洁性。需要注意的是,@Async注解的方法和调用者不应在同一类中,否则会失效。后续将分享实际项目中的@Async与CountDownLatch结合使用的案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在没有@Async注解之前我们需要写一个多线程低吗的话需要使用到JDK原生的多线程方法,代码十分冗余,当有了spring的@Async注解后就十分方便了,本次就详细介绍一下@Async注解的使用

  • 1创建线程池
    当在一个方法上标注了@Async注解之后,在被调用的时候主线程会主动使用多线程来调用此方法,但是当我们需要线程池来堆多线程进行管理的时候就需要使用到配置类线程池的Bean,如下
@Configuration
@EnableAsync
public class AsyncConfig {
    @Bean("getTaskExector")
    public Executor taskExecutor() {
        //通过Runtime方法来获取当前服务器cpu内核,根据cpu内核来创建核心线程数和最大线程数
        int threadCount = Runtime.getRuntime().availableProcessors();
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(threadCount);
        executor.setMaxPoolSize(threadCount);
        executor.setQueueCapacity(200);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("taskExecutor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor
### Spring Boot 中使用 `@Async` 实现异步方法的最佳实践 #### 1. 开启异步功能 为了使 `@Async` 注解生效,需要在应用程序的主或者配置上添加 `@EnableAsync` 注解。这一步是必要的,因为只有启用该注解后,Spring 才会识别并管理带有 `@Async` 的方法。 ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication @EnableAsync public class AsyncApplication { public static void main(String[] args) { SpringApplication.run(AsyncApplication.class, args); } } ``` 此部分的操作已在多个引用中提及[^2][^4]。 --- #### 2. 定义异步方法 任何希望被异步执行的方法都可以加上 `@Async` 注解。需要注意的是,默认情况下,这些方法会被放入由 Spring 创建的线程池中运行。 ```java import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class AsyncTaskService { @Async public void executeAsyncTask() { System.out.println("任务正在异步执行..."); } @Async public Future<String> executeAsyncWithResult() throws InterruptedException { Thread.sleep(2000); // 模拟耗时操作 return new AsyncResult<>("异步返回结果"); } } ``` 上述代码展示了两种常见的场景:一种是没有返回值的任务;另一种是有返回值的任务,并且可以通过 `Future` 对象获取其结果[^3]。 --- #### 3. 自定义线程池 虽然 Spring 默认提供了一个简单的线程池用于异步任务调度,但在实际生产环境中更推荐自定义线程池以满足特定需求。可以借助 `ThreadPoolTaskExecutor` 来完成这一目标: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @Configuration public class ThreadPoolConfig { @Bean(name = "taskExecutor") public ThreadPoolTaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); // 核心线程数 executor.setMaxPoolSize(10); // 最大线程数 executor.setQueueCapacity(25); // 队列容量 executor.initialize(); // 初始化线程池 return executor; } } ``` 通过这种方式,我们可以精确控制线程的数量及其行为模式,从而优化系统的性能表现[^1]。 --- #### 4. 超时处理机制 当某些异步任务可能长时间未响应时,我们需要为其设定合理的超时策略以防阻塞资源。下面是一个基于 `CompletableFuture` 的例子展示如何实现这一点: ```java import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; public String callWithTimeout(int timeoutInSeconds) throws ExecutionException, TimeoutException, InterruptedException { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(timeoutInSeconds * 1000L); // 模拟延迟 } catch (InterruptedException e) { throw new RuntimeException(e); } return "成功"; }, taskExecutor()); return future.get(timeoutInSeconds / 2, TimeUnit.SECONDS); // 设置一半时间为超时时限 } ``` 这里利用了 Java 提供的高级 API —— `CompletableFuture` 和它的 `get(long timeout, TimeUnit unit)` 方法来简化超时逻辑的设计。 --- #### 总结 以上就是关于如何在 Spring Boot 应用程序中有效运用 `@Async` 进行异步编程的一些最佳实践建议。合理调整线程池参数以及引入适当的错误恢复手段都是构建健壮服务不可或缺的部分。 ---
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值