SpringBoot_异步执行_Async

本文详细介绍SpringBoot中异步任务的配置方法,包括pom.xml依赖、bootstrap.yml配置及自定义TaskExecutor实现。通过@Component和@Async注解,轻松实现类方法的异步执行。

依赖pom.xml

配置文件bootstrap.yml

配置源码

/**
 * 
 * 使用方式:
 * 类上添加@Component
 * 类方法上添加@Async
 * 
 * Description: 异步执行配置类
 * @author Vander
 * @author 2018年4月26日
 * @version 0.8
 */
@Configuration
@EnableAsync
public class TaskExecutorConfig implements AsyncConfigurer{

	@Override
	public Executor getAsyncExecutor() {
		ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
		//TODO 后续配置文件注入参数
		taskExecutor.setCorePoolSize(5);
		taskExecutor.setMaxPoolSize(10);
		taskExecutor.setQueueCapacity(Integer.MAX_VALUE);
		taskExecutor.initialize();
		return taskExecutor;
	}

	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return null;
	}

}
### 3.1 启用 Spring Boot 异步调用支持 在 Spring Boot 中实现异步方法调用,首先需要启用异步支持。通过在主配置类或启动类上添加 `@EnableAsync` 注解,可以启用 Spring 的异步方法执行功能。该注解会触发 Spring 框架对带有 `@Async` 注解的方法进行代理,并在独立线程中执行这些方法,从而实现异步调用[^2]。 ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication @EnableAsync public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` ### 3.2 定义异步方法 在启用异步功能后,可以在任意 Spring 管理的 Bean 中定义异步方法。通过 `@Async` 注解标记的方法会在独立线程中执行,调用者无需等待方法执行完成即可继续执行后续逻辑。默认情况下,Spring 使用一个简单的线程池来管理异步任务。以下是一个无返回值的异步方法示例: ```java import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class AsyncService { @Async public void performAsyncTask() { // 模拟耗时操作 try { Thread.sleep(2000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } System.out.println("异步任务执行完成"); } } ``` ### 3.3 配置自定义线程池 默认情况下,Spring 使用单线程的 `SimpleAsyncTaskExecutor` 来执行异步任务。为了提高并发性能,建议自定义线程池配置。可以通过在配置类中定义 `TaskExecutor` Bean 来实现: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; @Configuration public class AsyncConfig { @Bean(name = "taskExecutor") public Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(100); executor.setThreadNamePrefix("Async-Executor-"); executor.initialize(); return executor; } } ``` 然后在异步方法上指定使用的执行器: ```java @Async("taskExecutor") public void performCustomPoolTask() { // 异步逻辑 System.out.println("使用自定义线程池执行异步任务"); } ``` ### 3.4 有返回值的异步方法 Spring 支持带有返回值的异步方法调用,返回值类型为 `Future` 或其子类 `AsyncResult`。此类方法可以在执行完成后返回结果给调用者: ```java import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.util.concurrent.AsyncResult; import java.util.concurrent.Future; @Service public class AsyncService { @Async public Future<String> performAsyncWithResult() { try { Thread.sleep(3000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return new AsyncResult<>("异步任务完成并返回结果"); } } ``` 调用方可以通过 `Future` 对象获取异步执行结果: ```java Future<String> result = asyncService.performAsyncWithResult(); System.out.println(result.get()); // 阻塞直到结果返回 ``` ### 3.5 注意事项 - 异步方法必须位于 Spring 管理的 Bean 中,且不能是 `private` 方法。 - 同一个类中调用 `@Async` 方法不会触发异步行为,因为代理机制不适用于内部调用。 - 异步方法默认不传播事务上下文,如需事务支持,应显式配置事务管理器。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值