gpt4 book ai didi

java - 如何提高RestTemplate的性能

转载 作者:行者123 更新时间:2023-11-30 01:45:46 26 4
gpt4 key购买 nike

我正在编写一个 Spring Boot 应用程序并使用 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。

@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}

第二,尝试获取 Object.class 而不是 JsonNode.class

第三,如果您不需要实体而是对象本身,请尝试 getForObject()

第四,给出 this一读。这是 spring 在幕后用于 JSON 序列化/反序列化的库。

关于java - 如何提高RestTemplate的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58053601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com