问题
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;
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
回答1:
If I am reading your question right I believe you want to make parallel calls and combine the results, and in that case I would suggest you to make use of TestNG. I had a similar requirement in the past and this link helped me out
Here's a sample code
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);
}
}
Just remove (parallel = true)
to see how it works sequentially. I have extracted the email field from the response using JSONPath and added to the list
Don't forget to update the POM
回答2:
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)
来源:https://stackoverflow.com/questions/62165362/make-multiple-api-calls-and-return-combined-response-in-minimum-time