gpt4 book ai didi

java - 使用新的 RestTemplate 与restTemplateBuilder 创建 RestTemplate

转载 作者:行者123 更新时间:2023-12-02 09:36:02 36 4
gpt4 key购买 nike

这种方式创建RestTemplate有什么区别

RestTemplate restTemplate = restTemplateBuilder
.setConnectTimeout(Duration.ofMillis(connectTimeout))
.setReadTimeout(Duration.ofMillis(readTimeout))
.build();

这样

CloseableHttpClient httpClient = HttpClientBuilder.create().disableCookieManagement().build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);

factory.setReadTimeout(readTimeout);
factory.setConnectTimeout(connectTimeout);
RestTemplate restTemplate = new RestTemplate(factory);

???

最佳答案

我认为你对 Scope RestTemplateBuilder 的问题。正如 Spring 文档中提到的:

Scope of restTemplateBuilder

To make the scope of any customizations as narrow as possible, inject the auto-configured RestTemplateBuilder and then call its methods as required. Each method call returns a new RestTemplateBuilder instance, so the customizations only affect this use of the builder.

示例:

private RestTemplate restTemplate;

@Autowired
public HelloController(RestTemplateBuilder builder) {
this.restTemplate = builder.build();
}

To make an application-wide, additive customization, use a RestTemplateCustomizer bean. All such beans are automatically registered with the auto-configured RestTemplateBuilder and are applied to any templates that are built with it.

示例

static class ProxyCustomizer implements RestTemplateCustomizer {

@Override
public void customize(RestTemplate restTemplate) {
HttpHost proxy = new HttpHost("proxy.example.com");
HttpClient httpClient = HttpClientBuilder.create().setRoutePlanner(new DefaultProxyRoutePlanner(proxy) {

@Override
public HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context)
throws HttpException {
if (target.getHostName().equals("192.168.0.5")) {
return null;
}
return super.determineProxy(target, request, context);
}

}).build();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
}

}

注意:使用RestTemplateBuilder缩小范围。对于应用程序范围内使用 RestTemplateCustomizer

引用链接:Reference link

其他详细信息示例:Additional example

关于java - 使用新的 RestTemplate 与restTemplateBuilder 创建 RestTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57512238/

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