I am writing a Spring Boot application and using RestTemplate to send out a request.
Here is my method:
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.web.client.RestTemplate;
public static JsonNode getResponse(URI uri)
throws JsonParseException, JsonMappingException, IOException, URISyntaxException {
RestTemplate restTemplate = new RestTemplate();
return restTemplate.getForEntity(uri, JsonNode.class).getBody();
}
When I run the above method, it is taking roughly 3 seconds. When I run the same method in Postman, it is taking roughly 1 second.
What would account for this difference. Are there opportunities to improve the performance of RestTemplate?
First, declare restTemplate as a bean, instead of creating a new one every time.
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
Second, try getting Object.class
instead of JsonNode.class
.
Third, try getForObject()
if you don't need entity but the object itself.
Forth, give this a read. This is the library that spring uses behind the scenes for JSON serialization/deserialization.