【问题标题】:Make multiple API calls and return combined response in minimum time进行多次 API 调用并在最短的时间内返回组合响应
【发布时间】:2020-06-03 04:43:51
【问题描述】:

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

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

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

【问题讨论】:

  • 将每个电话都输入CompletableFuture.supplyAsync,然后将整个电话输入CompletableFuture.allOf。或者,如果您想要提前终止行为,请使用 CompletionService
  • 另外,不要使用宽松的 https 验证 - 这会禁用 https 并将整个 TLS 过程变成 CPU 周期的浪费。
  • 您需要使用连接池将其称为异步,以防您调用相同的主机。这将提高性能。

标签: java multithreading rest-assured


【解决方案1】:

如果我没看错你的问题,我相信你想进行并行调用并合并结果,在这种情况下,我建议你使用 TestNG。我过去有类似的要求,这个link 帮助了我

这是一个示例代码

public class Parallel {

    @DataProvider(parallel = true)
    public Object[] getURL() {
        return new Object[] { "https://reqres.in/api/users/1", "https://reqres.in/api/users/2",
                "https://reqres.in/api/users/3", "https://reqres.in/api/users/4", "https://reqres.in/api/users/5",
                "https://reqres.in/api/users/6" };
    }

    ArrayList<String> original = new ArrayList<String>();

    @Test(dataProvider = "getURL")
    public void stack(String url) {

        Response response = given().when().get(url);

        JsonPath js = response.jsonPath();

        String email = js.getString("data.email");

        original.add(js.getString("data.email"));
    }

    @AfterTest
    public void simple() {
        System.out.println("List : " + original);
    }

}

只需删除 (parallel = true) 即可查看它是如何按顺序工作的。我已使用 JSONPath 从响应中提取电子邮件字段并添加到列表中

别忘了更新 POM

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-18
      • 2018-04-13
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      • 2019-08-03
      • 2020-04-13
      相关资源
      最近更新 更多