线程池配置类与CompletableFuture.runAsync集成方案
下面是一个完整的线程池配置类实现,结合了Spring Boot的配置管理,支持从配置文件读取参数,并提供了与CompletableFuture.runAsync的无缝集成。
完整实现代码
1. 线程池配置类 (ThreadPoolConfig.java)
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
public class ThreadPoolConfig {
@Value("${thread.pool.core-size:5}")
private int corePoolSize;
@Value("${thread.pool.max-size:10}")
private int maxPoolSize;
@Value("${thread.pool.queue-capacity:50}")
private int queueCapacity;
@Value("${thread.pool.keep-alive-seconds:60}")
private int keepAliveSeconds;
@Value("${thread.pool.thread-name-prefix:'custom-async-'}")
private String threadNamePrefix;
@Bean("customTaskExecutor")
public Executor customTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心配置
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAliveSeconds);
executor.setThreadNamePrefix(threadNamePrefix);
// 拒绝策略:由调用线程处理该任务
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 初始化
executor.initialize();
return executor;
}
}
2. 应用配置文件 (application.yml)
# 线程池配置
thread:
pool:
core-size: 8
max-size: 20
queue-capacity: 100
keep-alive-seconds: 120
thread-name-prefix: "app-async-"
3. 服务类使用示例 (AsyncTaskService.java)
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
@Service
public class AsyncTaskService {
private final Executor customExecutor;
@Autowired
public AsyncTaskService(@Qualifier("customTaskExecutor") Executor customExecutor) {
this.customExecutor = customExecutor;
}
// 使用CompletableFuture.runAsync执行异步任务
public CompletableFuture<Void> executeAsyncTask(Runnable task) {
return CompletableFuture.runAsync(task, customExecutor);
}
// 或者使用Spring的@Async注解
@Async("customTaskExecutor")
public CompletableFuture<Void> executeWithAsyncAnnotation() {
// 执行异步任务逻辑
return CompletableFuture.completedFuture(null);
}
// 批量执行任务示例
public void executeMultipleTasks() {
for (int i = 0; i < 10; i++) {
final int taskId = i;
executeAsyncTask(() -> {
System.out.println(Thread.currentThread().getName() + " 执行任务 #" + taskId);
// 模拟任务执行
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
}
// 带结果返回的示例
public CompletableFuture<String> fetchDataAsync() {
return CompletableFuture.supplyAsync(() -> {
// 模拟数据获取
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return "Error";
}
return "Data from async task";
}, customExecutor);
}
}
4. 控制器示例 (TaskController.java)
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.concurrent.CompletableFuture;
@RestController
public class TaskController {
@Autowired
private AsyncTaskService asyncTaskService;
@GetMapping("/run-task")
public String runTask() {
asyncTaskService.executeAsyncTask(() -> {
System.out.println("执行后台任务...");
// 实际任务逻辑
});
return "任务已提交";
}
@GetMapping("/run-multiple")
public String runMultipleTasks() {
asyncTaskService.executeMultipleTasks();
return "批量任务已提交";
}
@GetMapping("/fetch-data")
public CompletableFuture<String> fetchData() {
return asyncTaskService.fetchDataAsync();
}
}
配置详解
线程池参数说明
| 参数名 | 默认值 | 说明 |
|---|---|---|
| corePoolSize | 5 | 核心线程数,即使空闲也不会被回收 |
| maxPoolSize | 10 | 最大线程数 |
| queueCapacity | 50 | 任务队列容量 |
| keepAliveSeconds | 60 | 非核心线程空闲存活时间(秒) |
| threadNamePrefix | "custom-async-" | 线程名前缀 |
拒绝策略选项
Spring的ThreadPoolTaskExecutor支持以下拒绝策略:
-
AbortPolicy(默认):抛出RejectedExecutionException
-
CallerRunsPolicy:由调用线程执行该任务
-
DiscardPolicy:直接丢弃任务
-
DiscardOldestPolicy:丢弃队列中最旧的任务

浙公网安备 33010602011771号