据我所知,RestTemplateBuilder
是 RestTemplate
的某种工厂。我有几个关于使用它的问题:
在示例中,
@Configuration
类中经常有这样的内容:@Bean public RestTemplate getRestClient() { RestTemplate restClient = new RestTemplate(); ... return restClient; }
RestTemplate
不应该为每个@Service
类实例化吗?如果可以,如何定制?Spring 引用说明
RestTemplateBuilder
应该通过RestTemplateCustomizer
进行自定义。如何使用一个构建器管理来自多个 IP 地址的多个 URI?如何通过
RestTemplateBuilder
将BasicAuthentication
全局添加到所有RestTemplates
,这是一个好的做法吗?
感谢您的帮助。
更新:
我的应用程序从不同 IP 和 URL 的许多服务器调用休息服务 - 所以逻辑上对我来说是当我有很多 RestTemplates
的情况。
我正在尝试为每台服务器创建一个工厂 (RestTemplateBuilder
) - 比如说服务器 A、B、C。我知道如何添加基本身份验证。但是,例如当我想要服务器 A 而不是服务器 B 的基本身份验证时怎么办?
我考虑在每台服务器上安装一个 RestTemplateBuilder
。我不想手动执行此操作 - 我更愿意使用 Spring 机制。
有什么帮助吗?
最佳答案
不,你不需要,通常你会有一个 rest 模板实例,你会传递不同的 url,并且每次都相应地请求参数。
String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings/{booking}", String.class, vars); Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class);
来自 spring doc 的描述性示例,您可以向构建器添加尽可能多的定制器
public 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)); } }
Any RestTemplateCustomizer beans will be automatically added to the auto-configured RestTemplateBuilder. Furthermore, a new RestTemplateBuilder with additional customizers can be created by calling additionalCustomizers(RestTemplateCustomizer…)
@Bean
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder()
.rootUri(rootUri)
.basicAuthorization(username, password);
}
关于java - Spring Boot - 休息模板和休息模板构建器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39957550/