使用SpringBoot异步编程并行处理数据
发表于 2025-11-12
异步编程在高并发场景下,可以显著提高应用程序的响应速度和吞吐量。而SpringBoot则提供了简单方便的@Async注解用于实现异步编程。本文将以一个例子来简述该注解的基础使用方法
如何使用@Async注解
要使用 @Async 注解,首先需要在配置类上添加 @EnableAsync 注解来启用异步支持。然后,在需要异步执行的方法上添加 @Async 注解即可。
示例
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean("taskExecutor")
public ThreadPoolTaskExecutor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心线程池大小
executor.setCorePoolSize(2);
// 最大线程数
executor.setMaxPoolSize(4);
// 配置队列容量,默认值为Integer.MAX_VALUE
executor.setQueueCapacity(50);
// 线程名字前缀
executor.setThreadNamePrefix("worker-");
executor.initialize();
return executor;
}
}
编辑中……
Java
public CompletableFuture<JobInfo> doSomething(Map<String, Object> param) {
return CompletableFuture.supplyAsync(() -> {
String threadName = Thread.currentThread().getName();
System.out.println(String.format("%s线程开始咯", threadName));
try {
Thread.sleep(5000); // 模拟耗时操作
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted", e);
}
System.out.println(String.format("%s线程结束了咯", threadName));
return result;
});
}