线程池配置
package com.fast.boot.framework.config;
import com.fast.boot.common.config.ThreadPoolProperties;
import com.fast.boot.common.utils.ThreadsUtils;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import javax.annotation.Resource;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
@EnableAsync
@Configuration
@EnableConfigurationProperties(value = ThreadPoolProperties.class)
public class ThreadPoolConfig {
@Resource
private ThreadPoolProperties threadPoolProperties;
@Bean(name = "threadPoolTaskExecutor")
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadNamePrefix(threadPoolProperties.getThreadCustomPrefix());
executor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
executor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
executor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
executor.initialize();
return executor;
}
@Bean(name = "scheduledExecutorService")
protected ScheduledExecutorService scheduledExecutorService() {
return new ScheduledThreadPoolExecutor(threadPoolProperties.getCorePoolSize(),
new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build(),
new ThreadPoolExecutor.CallerRunsPolicy()) {
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
ThreadsUtils.printException(r, t);
}
};
}
}
模拟测试
package com.fast.boot.web.controller.common;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSON;
import com.fast.boot.common.annotation.GlobalResult;
import com.fast.boot.mail.service.MailService;
import com.fast.boot.model.AjaxResult;
import com.fast.boot.model.Result;
import com.fast.boot.service.sdk.CommonService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/common")
@RequiredArgsConstructor
@Slf4j
public class CommonController {
@Resource
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
@ApiOperation(value = "测试接口")
@GetMapping("test")
public AjaxResult<?> test(String key, Integer len) {
log.info("测试 :{}", key);
test(len);
return AjaxResult.success("测试");
}
@ApiOperation(value = "测试接口3")
@GetMapping("test3")
@GlobalResult
public Integer test3(String key, Integer count) {
log.info("异步测试 :{}", key);
List<String> searchList = new ArrayList<>();
for (int i = 0; i < count; i++) {
searchList.add(System.currentTimeMillis() + "" + i);
}
List<Callable<Map<String, Object>>> tasks = searchList.stream()
.map(item -> (Callable<Map<String, Object>>) () -> buildResultMap(item))
.collect(Collectors.toList());
List<Map<String, Object>> res = execQuery(tasks);
log.info("test3异步结果:" + JSON.toJSONString(res));
return 3;
}
public void test(Integer count) {
log.info("执行并行、串行测试: count=" + count);
List<Long> searchList = new ArrayList<>();
for (long i = count; i > 0; i--) {
searchList.add(System.currentTimeMillis() + i);
}
long asyncStart = System.currentTimeMillis();
List<String> completableFutureList = searchList.parallelStream()
.map(first -> CompletableFuture.supplyAsync(() -> getSearchResult(first), threadPoolTaskExecutor))
.map(second -> second.thenApply(this::queryB))
.map(third -> third.thenApply(this::queryB))
.map(CompletableFuture::join)
.filter(Objects::nonNull)
.collect(Collectors.toList());
long elapsedTime = System.currentTimeMillis() - asyncStart;
log.info("并行:" + elapsedTime);
asyncStart = System.currentTimeMillis();
List<String> completableFutureList2 = searchList.parallelStream()
.map(this::getSearchResult)
.map(this::queryB)
.map(this::queryB)
.filter(Objects::nonNull)
.collect(Collectors.toList());
elapsedTime = System.currentTimeMillis() - asyncStart;
log.info("串行:" + elapsedTime);
}
public String getSearchResult(long orderId) {
ThreadUtil.safeSleep(50);
return "getSearchResult--测试:" + orderId;
}
public String queryB(String s) {
ThreadUtil.safeSleep(50);
return "queryB" + s;
}
protected <U> List<U> execQuery(List<Callable<U>> tasks) {
try {
List<Future<U>> results = threadPoolTaskExecutor.getThreadPoolExecutor().invokeAll(tasks);
return results.stream().map(item -> {
try {
return item.get();
} catch (Exception e) {
log.error("【execQuery】异步执行结果获取异常", e);
}
return null;
}).collect(Collectors.toList());
} catch (Exception e) {
log.error("【execQuery】异步执行异常", e);
}
return Collections.emptyList();
}
private Map<String, Object> buildResultMap(String s) {
Map<String, Object> map = new HashMap<>();
map.put("testId", s);
ThreadUtil.safeSleep(RandomUtil.randomInt(100));
return map;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)