【问题标题】:Creating RestTemplate with new RestTemplate vs restTemplateBuilder使用新的 RestTemplate 与 restTemplateBuilder 创建 RestTemplate
【发布时间】:2019-08-15 15:37:16
【问题描述】:

这样创建 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);

??????

【问题讨论】:

  • 首先,restTemplateBuilder 可能有额外的配置,例如拦截器(分布式跟踪和指标很常见)。

标签: java spring rest spring-mvc


【解决方案1】:

我认为您关于 Scope restTemplateBuilder 的问题。正如 Spring 文档中提到的那样:

Scope of restTemplateBuilder

为了使任何自定义的范围尽可能缩小,注入 自动配置的 RestTemplateBuilder ,然后将其方法称为 必需的。每个方法调用都会返回一个新的 RestTemplateBuilder 实例, 所以自定义只会影响构建器的这种使用。

例子:

private RestTemplate restTemplate;

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

要进行应用程序范围的附加自定义,请使用 RestTemplateCustomizer bean。所有这些 bean 都会自动 使用自动配置的 RestTemplateBuilder 注册并且 应用于使用它构建的任何模板。

例子

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

【讨论】:

    猜你喜欢
    • 2018-01-22
    • 2018-08-14
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    • 2021-12-06
    相关资源
    最近更新 更多