在最短的时间内进行多次 API 调用并返回组合响应 [英] Make multiple API calls and return combined response in minimum time

查看:70
本文介绍了在最短的时间内进行多次 API 调用并返回组合响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 10 个健康检查 URL,它们只是获取服务我像下面这样循环击打它们

I have 10 health check URLs which are simply get service I am hitting them in a loop like below

for(int i=0;i<10;i++){
  Response response = given().when().relaxedHttpsValidation().get(url[i]);
   list.add(response);
  }
   return list;

现在的问题是它串联命中 API 并等待所有响应,我只想并行命中所有 API 但合并结果,我尝试使用线程但无法了解如何合并响应在多线程的情况下

Now the problem is it hits API in series and waiting for a response for all, I just want to hit all API in parallel but combine the result, I tried using threads but unable to get an idea on how to combine the response in case of multi-threading

推荐答案

感谢您的快速回复,我现在只想分享我是如何实现的

Thank you for your quick response i just want to share now how i achieved it

List responseList = new ArrayList();
ExecutorService exec = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
exec.submit(new Runnable() {
    public void run() {
        String response = executeServiceCall(urlArray[i]);
        responseList.add(response);
     }
   });
} exec.shutdown();
 try {
exec.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
 } catch (InterruptedException e) {
  LOGGER.error(e.toString());
}
 LOGGER.info("response list is " + responseList)

这篇关于在最短的时间内进行多次 API 调用并返回组合响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆