如何提高 RestTemplate 的性能
How to improve performance of RestTemplate
我正在编写 Spring 引导应用程序并使用 RestTemplate 发送请求。
这是我的方法:
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();
}
当我运行上述方法时,大约需要3秒。当我 运行 在 Postman 中使用相同的方法时,大约需要 1 秒。
造成这种差异的原因是什么。有机会提高 RestTemplate 的性能吗?
首先,将restTemplate声明为一个bean,而不是每次都创建一个新的。
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
第二,尝试获取 Object.class
而不是 JsonNode.class
。
第三种,如果您不需要实体而是对象本身,请尝试getForObject()
。
第四,给this读一读。这是 spring 在幕后为 JSON serialization/deserialization 使用的库。
我正在编写 Spring 引导应用程序并使用 RestTemplate 发送请求。
这是我的方法:
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();
}
当我运行上述方法时,大约需要3秒。当我 运行 在 Postman 中使用相同的方法时,大约需要 1 秒。
造成这种差异的原因是什么。有机会提高 RestTemplate 的性能吗?
首先,将restTemplate声明为一个bean,而不是每次都创建一个新的。
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
第二,尝试获取 Object.class
而不是 JsonNode.class
。
第三种,如果您不需要实体而是对象本身,请尝试getForObject()
。
第四,给this读一读。这是 spring 在幕后为 JSON serialization/deserialization 使用的库。