1. ThreadPoolTaskExecutor概述

ThreadPoolTaskExecutor是Spring框架提供的线程池任务执行器,基于Java的ThreadPoolExecutor实现,提供了更高级的线程池管理功能。本文将详细介绍ThreadPoolTaskExecutor的原理、配置、异步任务执行和性能优化。

1.1 核心功能

  1. 线程池管理: 核心线程、最大线程、队列、拒绝策略
  2. 异步任务执行: @Async注解、异步方法调用
  3. 任务调度: 定时任务、延迟任务、周期任务
  4. 线程池配置: 参数配置、监控配置、性能配置
  5. 性能优化: 线程复用、资源管理、并发控制

1.2 技术架构

1
2
3
4
5
任务提交 → ThreadPoolTaskExecutor → 线程池 → 任务执行 → 结果返回
↓ ↓ ↓ ↓ ↓
异步方法 → 任务调度器 → 线程管理 → 资源分配 → 性能优化
↓ ↓ ↓ ↓ ↓
@Async → 任务队列 → 线程复用 → 监控告警 → 系统优化

2. ThreadPoolTaskExecutor配置

2.1 Maven依赖配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!-- pom.xml -->
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- Spring Boot Actuator -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<!-- Micrometer -->
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

<!-- Apache Commons Lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>

<!-- Guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
</dependencies>

2.2 ThreadPoolTaskExecutor配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/**
* ThreadPoolTaskExecutor配置类
*/
@Configuration
@EnableAsync
public class ThreadPoolTaskExecutorConfig {

@Value("${thread-pool.core-pool-size:10}")
private int corePoolSize;

@Value("${thread-pool.max-pool-size:50}")
private int maxPoolSize;

@Value("${thread-pool.queue-capacity:1000}")
private int queueCapacity;

/**
* ThreadPoolTaskExecutor配置属性
*/
@Bean
public ThreadPoolTaskExecutorProperties taskExecutorProperties() {
return ThreadPoolTaskExecutorProperties.builder()
.corePoolSize(corePoolSize)
.maxPoolSize(maxPoolSize)
.queueCapacity(queueCapacity)
.build();
}

/**
* 默认线程池任务执行器
*/
@Bean("taskExecutor")
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("TaskExecutor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
executor.initialize();
return executor;
}

/**
* 异步任务执行器
*/
@Bean("asyncTaskExecutor")
public ThreadPoolTaskExecutor asyncTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("AsyncTask-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
executor.initialize();
return executor;
}

/**
* 定时任务执行器
*/
@Bean("scheduledTaskExecutor")
public ThreadPoolTaskExecutor scheduledTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("ScheduledTask-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
executor.initialize();
return executor;
}

/**
* 线程池管理器
*/
@Bean
public ThreadPoolTaskExecutorManager taskExecutorManager() {
return new ThreadPoolTaskExecutorManager(taskExecutorProperties());
}

/**
* 线程池监控器
*/
@Bean
public ThreadPoolTaskExecutorMonitor taskExecutorMonitor() {
return new ThreadPoolTaskExecutorMonitor(taskExecutorProperties());
}
}

/**
* ThreadPoolTaskExecutor配置属性
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ThreadPoolTaskExecutorProperties {
private int corePoolSize;
private int maxPoolSize;
private int queueCapacity;

// 线程池配置
private long keepAliveSeconds = 60;
private String threadNamePrefix = "TaskExecutor-";
private boolean allowCoreThreadTimeOut = false;
private String rejectedExecutionHandler = "CallerRunsPolicy";

// 异步配置
private boolean enableAsync = true;
private String asyncExecutorName = "asyncTaskExecutor";
private boolean enableAsyncMethodSecurity = true;

// 监控配置
private boolean enableMonitoring = true;
private int monitoringInterval = 60; // 秒
private boolean enableMetrics = true;

// 性能配置
private boolean enablePerformanceOptimization = true;
private int maxConcurrentTasks = 1000;
private boolean enableDynamicScaling = true;
}

3. ThreadPoolTaskExecutor管理器

3.1 ThreadPoolTaskExecutor管理器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
/**
* ThreadPoolTaskExecutor管理器
*/
@Component
public class ThreadPoolTaskExecutorManager {

private final ThreadPoolTaskExecutorProperties properties;
private final Map<String, ThreadPoolTaskExecutor> executors = new ConcurrentHashMap<>();

public ThreadPoolTaskExecutorManager(ThreadPoolTaskExecutorProperties properties) {
this.properties = properties;
}

/**
* 创建ThreadPoolTaskExecutor
* @param executorName 执行器名称
* @return ThreadPoolTaskExecutor
*/
public ThreadPoolTaskExecutor createTaskExecutor(String executorName) {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(properties.getCorePoolSize());
executor.setMaxPoolSize(properties.getMaxPoolSize());
executor.setQueueCapacity(properties.getQueueCapacity());
executor.setKeepAliveSeconds(properties.getKeepAliveSeconds());
executor.setThreadNamePrefix(executorName + "-");
executor.setRejectedExecutionHandler(createRejectedExecutionHandler(properties.getRejectedExecutionHandler()));
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
executor.initialize();

executors.put(executorName, executor);
return executor;
}

/**
* 创建拒绝执行处理器
* @param handlerType 处理器类型
* @return 拒绝执行处理器
*/
private RejectedExecutionHandler createRejectedExecutionHandler(String handlerType) {
switch (handlerType.toLowerCase()) {
case "abortpolicy":
return new ThreadPoolExecutor.AbortPolicy();
case "callerrunspolicy":
return new ThreadPoolExecutor.CallerRunsPolicy();
case "discardpolicy":
return new ThreadPoolExecutor.DiscardPolicy();
case "discardoldestpolicy":
return new ThreadPoolExecutor.DiscardOldestPolicy();
default:
return new ThreadPoolExecutor.CallerRunsPolicy();
}
}

/**
* 获取执行器
* @param executorName 执行器名称
* @return ThreadPoolTaskExecutor
*/
public ThreadPoolTaskExecutor getTaskExecutor(String executorName) {
return executors.computeIfAbsent(executorName, this::createTaskExecutor);
}

/**
* 执行任务
* @param executorName 执行器名称
* @param task 任务
* @return Future
*/
public Future<?> executeTask(String executorName, Runnable task) {
ThreadPoolTaskExecutor executor = getTaskExecutor(executorName);
return executor.submit(task);
}

/**
* 执行任务(带返回值)
* @param executorName 执行器名称
* @param task 任务
* @param <T> 返回类型
* @return Future
*/
public <T> Future<T> executeTask(String executorName, Callable<T> task) {
ThreadPoolTaskExecutor executor = getTaskExecutor(executorName);
return executor.submit(task);
}

/**
* 获取执行器状态
* @param executorName 执行器名称
* @return 执行器状态
*/
public TaskExecutorStatus getTaskExecutorStatus(String executorName) {
ThreadPoolTaskExecutor executor = executors.get(executorName);
if (executor != null) {
ThreadPoolExecutor threadPoolExecutor = executor.getThreadPoolExecutor();

return TaskExecutorStatus.builder()
.executorName(executorName)
.corePoolSize(threadPoolExecutor.getCorePoolSize())
.maximumPoolSize(threadPoolExecutor.getMaximumPoolSize())
.currentPoolSize(threadPoolExecutor.getPoolSize())
.activeThreadCount(threadPoolExecutor.getActiveCount())
.completedTaskCount(threadPoolExecutor.getCompletedTaskCount())
.totalTaskCount(threadPoolExecutor.getTaskCount())
.queueSize(threadPoolExecutor.getQueue().size())
.isShutdown(threadPoolExecutor.isShutdown())
.isTerminated(threadPoolExecutor.isTerminated())
.build();
}

return TaskExecutorStatus.builder().executorName(executorName).build();
}

/**
* 关闭执行器
* @param executorName 执行器名称
* @param timeout 超时时间
* @param unit 时间单位
* @return 是否成功关闭
*/
public boolean shutdownTaskExecutor(String executorName, long timeout, TimeUnit unit) {
try {
ThreadPoolTaskExecutor executor = executors.get(executorName);
if (executor != null) {
executor.shutdown();
return executor.getThreadPoolExecutor().awaitTermination(timeout, unit);
}
return true;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
}

/**
* 任务执行器状态
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class TaskExecutorStatus {
private String executorName;
private int corePoolSize;
private int maximumPoolSize;
private int currentPoolSize;
private int activeThreadCount;
private long completedTaskCount;
private long totalTaskCount;
private int queueSize;
private boolean isShutdown;
private boolean isTerminated;
}

4. 异步任务执行服务

4.1 异步任务执行服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/**
* 异步任务执行服务
*/
@Service
public class AsyncTaskExecutionService {

private final ThreadPoolTaskExecutorManager taskExecutorManager;

public AsyncTaskExecutionService(ThreadPoolTaskExecutorManager taskExecutorManager) {
this.taskExecutorManager = taskExecutorManager;
}

/**
* 异步执行任务
* @param taskName 任务名称
* @param duration 执行时间(毫秒)
* @return CompletableFuture
*/
@Async("asyncTaskExecutor")
public CompletableFuture<String> executeAsyncTask(String taskName, int duration) {
try {
log.info("异步任务开始执行: {}", taskName);
Thread.sleep(duration);
log.info("异步任务执行完成: {}", taskName);
return CompletableFuture.completedFuture("任务执行成功: " + taskName);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("异步任务被中断: {}", taskName);
return CompletableFuture.completedFuture("任务被中断: " + taskName);
} catch (Exception e) {
log.error("异步任务执行失败: {}", taskName, e);
return CompletableFuture.completedFuture("任务执行失败: " + taskName);
}
}

/**
* 异步执行任务(带返回值)
* @param taskName 任务名称
* @param duration 执行时间(毫秒)
* @param result 返回结果
* @param <T> 返回类型
* @return CompletableFuture
*/
@Async("asyncTaskExecutor")
public <T> CompletableFuture<T> executeAsyncTaskWithResult(String taskName, int duration, T result) {
try {
log.info("异步任务开始执行: {}", taskName);
Thread.sleep(duration);
log.info("异步任务执行完成: {}", taskName);
return CompletableFuture.completedFuture(result);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("异步任务被中断: {}", taskName);
throw new RuntimeException("任务被中断: " + taskName, e);
} catch (Exception e) {
log.error("异步任务执行失败: {}", taskName, e);
throw new RuntimeException("任务执行失败: " + taskName, e);
}
}

/**
* 批量异步执行任务
* @param tasks 任务列表
* @return CompletableFuture列表
*/
public List<CompletableFuture<String>> executeBatchAsyncTasks(List<AsyncTask> tasks) {
List<CompletableFuture<String>> futures = new ArrayList<>();

for (AsyncTask task : tasks) {
CompletableFuture<String> future = executeAsyncTask(task.getTaskName(), task.getDuration());
futures.add(future);
}

return futures;
}

/**
* 等待所有异步任务完成
* @param futures CompletableFuture列表
* @param timeout 超时时间
* @param unit 时间单位
* @return 是否全部完成
*/
public boolean waitForAllAsyncTasks(List<CompletableFuture<String>> futures, long timeout, TimeUnit unit) {
try {
CompletableFuture<Void> allFutures = CompletableFuture.allOf(
futures.toArray(new CompletableFuture[0]));
allFutures.get(timeout, unit);
return true;
} catch (Exception e) {
log.error("等待异步任务完成失败", e);
return false;
}
}

/**
* 异步执行任务(手动指定执行器)
* @param executorName 执行器名称
* @param task 任务
* @return Future
*/
public Future<?> executeTaskWithExecutor(String executorName, Runnable task) {
return taskExecutorManager.executeTask(executorName, task);
}

/**
* 异步执行任务(带返回值,手动指定执行器)
* @param executorName 执行器名称
* @param task 任务
* @param <T> 返回类型
* @return Future
*/
public <T> Future<T> executeTaskWithExecutor(String executorName, Callable<T> task) {
return taskExecutorManager.executeTask(executorName, task);
}
}

/**
* 异步任务
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AsyncTask {
private String taskName;
private int duration; // 毫秒
}

5. 任务调度服务

5.1 任务调度服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* 任务调度服务
*/
@Service
public class TaskSchedulingService {

private final ThreadPoolTaskExecutorManager taskExecutorManager;

public TaskSchedulingService(ThreadPoolTaskExecutorManager taskExecutorManager) {
this.taskExecutorManager = taskExecutorManager;
}

/**
* 延迟执行任务
* @param taskName 任务名称
* @param task 任务
* @param delay 延迟时间
* @param unit 时间单位
* @return ScheduledFuture
*/
public ScheduledFuture<?> scheduleTask(String taskName, Runnable task, long delay, TimeUnit unit) {
ThreadPoolTaskExecutor executor = taskExecutorManager.getTaskExecutor("scheduledTaskExecutor");
ScheduledExecutorService scheduledExecutor = executor.getScheduledExecutor();

return scheduledExecutor.schedule(task, delay, unit);
}

/**
* 定时执行任务
* @param taskName 任务名称
* @param task 任务
* @param initialDelay 初始延迟
* @param period 执行周期
* @param unit 时间单位
* @return ScheduledFuture
*/
public ScheduledFuture<?> scheduleAtFixedRate(String taskName, Runnable task,
long initialDelay, long period, TimeUnit unit) {
ThreadPoolTaskExecutor executor = taskExecutorManager.getTaskExecutor("scheduledTaskExecutor");
ScheduledExecutorService scheduledExecutor = executor.getScheduledExecutor();

return scheduledExecutor.scheduleAtFixedRate(task, initialDelay, period, unit);
}

/**
* 定时执行任务(固定延迟)
* @param taskName 任务名称
* @param task 任务
* @param initialDelay 初始延迟
* @param delay 延迟时间
* @param unit 时间单位
* @return ScheduledFuture
*/
public ScheduledFuture<?> scheduleWithFixedDelay(String taskName, Runnable task,
long initialDelay, long delay, TimeUnit unit) {
ThreadPoolTaskExecutor executor = taskExecutorManager.getTaskExecutor("scheduledTaskExecutor");
ScheduledExecutorService scheduledExecutor = executor.getScheduledExecutor();

return scheduledExecutor.scheduleWithFixedDelay(task, initialDelay, delay, unit);
}

/**
* 取消定时任务
* @param scheduledFuture 定时任务Future
* @return 是否取消成功
*/
public boolean cancelScheduledTask(ScheduledFuture<?> scheduledFuture) {
return scheduledFuture.cancel(false);
}

/**
* 获取定时任务状态
* @param scheduledFuture 定时任务Future
* @return 任务状态
*/
public ScheduledTaskStatus getScheduledTaskStatus(ScheduledFuture<?> scheduledFuture) {
return ScheduledTaskStatus.builder()
.isDone(scheduledFuture.isDone())
.isCancelled(scheduledFuture.isCancelled())
.remainingDelay(scheduledFuture.getDelay(TimeUnit.MILLISECONDS))
.build();
}
}

/**
* 定时任务状态
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ScheduledTaskStatus {
private boolean isDone;
private boolean isCancelled;
private long remainingDelay; // 毫秒
}

6. ThreadPoolTaskExecutor控制器

6.1 ThreadPoolTaskExecutor控制器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
/**
* ThreadPoolTaskExecutor控制器
*/
@RestController
@RequestMapping("/api/v1/thread-pool-task-executor")
public class ThreadPoolTaskExecutorController {

@Autowired
private ThreadPoolTaskExecutorManager taskExecutorManager;

@Autowired
private AsyncTaskExecutionService asyncTaskExecutionService;

@Autowired
private TaskSchedulingService taskSchedulingService;

/**
* 创建任务执行器
*/
@PostMapping("/create")
public ResponseEntity<Map<String, Object>> createTaskExecutor(@RequestBody TaskExecutorRequest request) {
try {
ThreadPoolTaskExecutor executor = taskExecutorManager.createTaskExecutor(request.getExecutorName());

Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("message", "任务执行器创建成功");
response.put("executorName", request.getExecutorName());

return ResponseEntity.ok(response);

} catch (Exception e) {
log.error("创建任务执行器失败", e);

Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "创建任务执行器失败: " + e.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}

/**
* 执行异步任务
*/
@PostMapping("/execute-async")
public ResponseEntity<Map<String, Object>> executeAsyncTask(@RequestBody AsyncTaskRequest request) {
try {
CompletableFuture<String> future = asyncTaskExecutionService.executeAsyncTask(
request.getTaskName(), request.getDuration());

Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("message", "异步任务提交成功");
response.put("taskName", request.getTaskName());

return ResponseEntity.ok(response);

} catch (Exception e) {
log.error("执行异步任务失败", e);

Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "执行异步任务失败: " + e.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}

/**
* 获取任务执行器状态
*/
@GetMapping("/status")
public ResponseEntity<Map<String, Object>> getTaskExecutorStatus(@RequestParam String executorName) {
try {
TaskExecutorStatus status = taskExecutorManager.getTaskExecutorStatus(executorName);

Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("status", status);

return ResponseEntity.ok(response);

} catch (Exception e) {
log.error("获取任务执行器状态失败", e);

Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "获取任务执行器状态失败: " + e.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}

/**
* 调度任务
*/
@PostMapping("/schedule")
public ResponseEntity<Map<String, Object>> scheduleTask(@RequestBody ScheduleTaskRequest request) {
try {
Runnable task = new Runnable() {
@Override
public void run() {
log.info("定时任务执行: {}", request.getTaskName());
}
};

ScheduledFuture<?> scheduledFuture = taskSchedulingService.scheduleTask(
request.getTaskName(), task, request.getDelay(), TimeUnit.MILLISECONDS);

Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("message", "任务调度成功");
response.put("taskName", request.getTaskName());

return ResponseEntity.ok(response);

} catch (Exception e) {
log.error("调度任务失败", e);

Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "调度任务失败: " + e.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}
}

/**
* 任务执行器请求模型
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TaskExecutorRequest {
private String executorName;
}

/**
* 异步任务请求模型
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AsyncTaskRequest {
private String taskName;
private int duration; // 毫秒
}

/**
* 调度任务请求模型
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ScheduleTaskRequest {
private String taskName;
private long delay; // 毫秒
}

7. 总结

通过ThreadPoolTaskExecutor的实现,我们成功构建了一个完整的Spring线程池管理框架。关键特性包括:

7.1 核心优势

  1. 线程池管理: 核心线程、最大线程、队列、拒绝策略
  2. 异步任务执行: @Async注解、异步方法调用
  3. 任务调度: 定时任务、延迟任务、周期任务
  4. 线程池配置: 参数配置、监控配置、性能配置
  5. 性能优化: 线程复用、资源管理、并发控制

7.2 最佳实践

  1. 线程池创建: 合理配置线程池参数、选择合适的拒绝策略
  2. 异步任务: 使用@Async注解、合理选择执行器
  3. 任务调度: 合理设置调度参数、及时取消不需要的任务
  4. 性能优化: 线程复用、资源管理、并发控制
  5. 系统优化: 基于监控数据进行系统优化

这套ThreadPoolTaskExecutor方案不仅能够提供完整的线程池管理能力,还包含了异步任务执行、任务调度、性能优化等核心功能,是企业级Spring应用的重要技术基础。