当前位置: 首页 > news >正文

springboot 使用CompletableFuture多线程调用多个url接口,等待所有接口返回后统一处理接口返回结果

1. 线程池配置,定义一个线程池,可以根据业务需求调整线程池的配置,以达到提高性能的目的

@Configuration
@EnableAsync
public class AsyncConfig {@Bean("apiTaskExecutor")public Executor taskExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(8);     // 核心线程数executor.setMaxPoolSize(10);      // 最大线程数executor.setQueueCapacity(50);    // 队列容量executor.setThreadNamePrefix("API-Thread-");executor.initialize();return executor;}
}

2. 异步调用第三方接口

接口调用返回类

@Data
@AllArgsConstructor
public class ApiResponse {private String apiName;         // API 标识private Object responseData;    // 原始响应数据(不同格式)private String errorMessage;    // 错误信息public ApiResponse(String apiName, Object responseData) {this.apiName = apiName;this.responseData = responseData;}
}
@Async("apiTaskExecutor")public CompletableFuture<ApiResponse> callApi(String apiName, String url, String param) {try {String result = HttpUtil.post(url, param);return CompletableFuture.completedFuture(new ApiResponse(apiName,result));} catch (Exception e) {return CompletableFuture.completedFuture(new ApiResponse(apiName, null, "API call failed: " + e.getMessage()));}}

3. 异步方法调用接口,apiConfig 里面保存了是接口名称,接口地址,接口参数,我删除了一部分代码,这个集合需要大家自己去组合,allFutures.thenApply处理接口返回,我这种逻辑可以根据不同的接口名称去处理不同的返回接口,然后统一处理业务逻辑

 @Async("apiTaskExecutor")public CompletableFuture<Map<String, Object>> aggregateApiResponses() {// 定义要调用的API列表Map<String, Map<String, String>> apiConfig = Map.of("riskAnalysis", Map.of("url", String.format("%s/riskAnalysis", aiHost), "param", JSON.toJSONString(risksJson, JSONWriter.Feature.WriteMapNullValue)),"bmi", Map.of("url", String.format("%s/BMI", aiHost), "param", bmiParam.toString()),"coreObjectiveAnalysis", Map.of("url", String.format("%s/coreObjectiveAnalysis", aiHost), "param", suggestionsJson.toString()),"suggestionsForCoreObjectives", Map.of("url", String.format("%s/suggestionsForCoreObjectives", aiHost), "param", suggestionsJson.toString()),"foodSuggestions", Map.of("url", String.format("%s/foodSuggestions", aiHost), "param", suggestionsJson.toString()),"sportSuggestions", Map.of("url", String.format("%s/sportSuggestions", aiHost), "param", suggestionsJson.toString()),"allSuggestions", Map.of("url", String.format("%s/allSuggestions", aiHost), "param", suggestionsJson.toString()));System.out.println(apiConfig);// 创建异步任务列表List<CompletableFuture<ApiResponse>> futures = apiConfig.entrySet().stream().map(entry -> {String apiName = entry.getKey();Map<String, String> params = entry.getValue();String url = params.get("url");String param = params.get("param");return surveysReportService.callApi(apiName, url, param);}).collect(Collectors.toList());// 组合所有异步任务CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));// 处理结果合并return allFutures.thenApply(voidd -> {futures.forEach(future -> {String apiName = "";try {ApiResponse response = future.get();apiName = response.getApiName();// 处理不同的响应结构switch (response.getApiName()) {case "bmi"://业务逻辑处理break;}} catch (Exception e) {//如果ai返回错误,则重试一次//throw new ServiceException("接口调用错误");}});//业务逻辑处理return null;});}


文章转载自:

http://0HwQQGhy.gkfwp.cn
http://cmMe0bbq.gkfwp.cn
http://oDxVb7zZ.gkfwp.cn
http://KAPdpx3Z.gkfwp.cn
http://cJWUfi4f.gkfwp.cn
http://hEyltnP0.gkfwp.cn
http://tRzWMcOl.gkfwp.cn
http://5wZNtlJz.gkfwp.cn
http://puK9TxPF.gkfwp.cn
http://RIZ6d3VI.gkfwp.cn
http://7uNN0HNH.gkfwp.cn
http://nAztI0cv.gkfwp.cn
http://d7AMJpTJ.gkfwp.cn
http://I4DRS9YH.gkfwp.cn
http://gpDIJpX7.gkfwp.cn
http://A3JbfgZe.gkfwp.cn
http://gbnzv3yd.gkfwp.cn
http://LNyXvTb9.gkfwp.cn
http://wzU8pazG.gkfwp.cn
http://L3gnqfNM.gkfwp.cn
http://9X1UNsUv.gkfwp.cn
http://OiF3IcfQ.gkfwp.cn
http://9Dbj49xd.gkfwp.cn
http://kE8vbxsg.gkfwp.cn
http://4uGUkdjO.gkfwp.cn
http://SAcwoBGL.gkfwp.cn
http://1dFdBdYG.gkfwp.cn
http://hPxszHH2.gkfwp.cn
http://2Dftakcz.gkfwp.cn
http://lVwB4Bbu.gkfwp.cn
http://www.dtcms.com/a/388587.html

相关文章:

  • 科普:build与make
  • 对比OpenCV GPU与CPU图像缩放的性能与效果差异
  • 网络工程师行业新技术新概念
  • 【Linux】Linux中dos2unix 工具转换文件格式
  • 实验4:表单控件绑定(2学时)
  • QT OpenCV 准备工具
  • 无锁化编程(Lock-Free Programming)分析
  • Centons7 docker 安装 playwright
  • 远距离传输大型文件:企业数字化转型的挑战与突破
  • 氧气科技亮相GDMS全球数字营销峰会,分享AI搜索时代GEO新观
  • useMemo和useCallback
  • 【数据结构---图的原理与最小生成树算法,单源最短路径算法】
  • 有发声生物(猫狗鸟等)与无发声生物(蚂蚁蝙蝠蛇等)的 “感知-->行动“
  • CC 攻击为什么越来越难防?
  • 量化交易 - Multiple Regression 多变量线性回归(机器学习)
  • 【机器学习】基于双向LSTM的IMDb情感分析
  • CLR-GAN训练自己的数据集
  • LeetCode 242 有效的字母异位词
  • 中州养老:Websocket实现报警通知
  • python+excel实现办公自动化学习
  • 深度学习快速复现平台AutoDL
  • 《股票智能查询与投资决策辅助应用项目方案》
  • nvm安装包分享【持续更新】
  • 2025年- H143-Lc344. 反转字符串(字符串)--Java版
  • 数据库的事务
  • Cadence SPB 2025安装教程(附安装包)Cadence SPB 24.1下载详细安装图文教程
  • .NET Framework 4.8 多线程编程
  • qt QHorizontalPercentBarSeries详解
  • 软考中级习题与解答——第七章_数据库系统(3)
  • Redis(基础数据类型/String)