I need to send the same request multiple times for example post request 100 times in the same time. My code look like this
@SpringBootTest
public class FetchApi {
String getUrl = "www.https://example/get";
String postUrl = "www.https://example/post";
String token = "adadfsdfgsdgdfgdfghdhdhdhdhdhdh";
@Test
public void getRequest() {
try {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " token);
HttpEntity<String> entity = new HttpEntity<>("", headers);
Object res = restTemplate.exchange(getUrl, HttpMethod.GET, entity, Object.class);
System.out.println(res);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void postRequest() {
try {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " token);
headers.setContentType(MediaType.APPLICATION_JSON);
Workflow workflow = new Workflow("adadadasdadadad", "1adadadadadadada0","adafsadfsfsdgfdsfgdfgdg");
String json = new ObjectMapper().writeValueAsString(workflow);
HttpEntity<String> entity = new HttpEntity<>(json, headers);
Object res = restTemplate.exchange(postUrl, HttpMethod.POST, entity, Object.class);
System.out.println(res);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
This code works fine if i have value from my class workflow but how to change to value from class to json file. My json file look that
{
"workflow":{
"guid":"adadadadadadadad"
},
"formType":{
"guid":"adadadadadadadad"
},
"formType":[
{
"guid":"adadadadadadadad",
"svalue":"adadadadadada"
},
"guid":"adadadadadadadad",
"svalue":"adadadadadada"
},
"guid":"adadadadadadadad",
"svalue":"adadadadadada"
}
]
}
Can someone give me information how to send a request multiple times at the same time with json ?
CodePudding user response:
You should look at ExecutorService
@Test
public void postRequest() {
ExecutorService executors = Executors.newFixedThreadPool(100);
try {
List<Callable<Object>> tasks = new ArrayList<>();
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " token);
headers.setContentType(MediaType.APPLICATION_JSON);
Workflow workflow = new Workflow("adadadasdadadad", "1adadadadadadada0", "adafsadfsfsdgfdsfgdfgdg");
String json = new ObjectMapper().writeValueAsString(workflow);
HttpEntity<String> entity = new HttpEntity<>(json, headers);
for (int i = 0; i < 100; i ) {
tasks.add(() ->
restTemplate.exchange(getUrl, HttpMethod.GET, entity, Object.class));
}
List<Future<Object>> futures = executors.invokeAll(tasks);
executors.awaitTermination(1, TimeUnit.MINUTES);
futures.forEach(objectFuture -> {
if(objectFuture.isDone()){
try {
System.out.println(objectFuture.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
executors.shutdown();
}
}