你好吗?我希望你做得很棒。
我正在为我的公司创建一个新的 Spring Boot 应用程序,对于这个特定的应用程序,我需要与不同的微服务进行通信,其中一些微服务具有不同的配置。例如:某些服务需要不同的 header 。
我不太确定如何以正确优雅的方式做到这一点。我采用的方法将“客户端”创建为 @Component,使用如下创建的其余模板与微服务进行通信:
@Component
public class ShifuClient {
private final RestTemplate restTemplate;
private static final String HOST = "http://example.com/service/";
@Autowired
public ShifuClient(RestTemplateBuilder builder) {
this.restTemplate = builder.build();
}
public ShifuDto getShifuTemplate(Locale locale) {
return this.restTemplate.getForObject(HOST+ "?locale={locale}", ShifuDto.class, locale.toString());
}
}
我还有一个用于应用程序范围定制器的 bean,它添加通用 header 并记录请求。
/**
* Customizes the creation of the {@link RestTemplate}
* used for connecting with other services.
* This configuration is application wide and applies to every request made with {@link RestTemplate}.
*/
public class ApplicationWideRestTemplateCustomizer implements RestTemplateCustomizer {
@Override
public void customize(RestTemplate restTemplate) {
restTemplate.getInterceptors().add(new AddHeadersRequestInterceptor());
restTemplate.getInterceptors().add(new LogRequestInterceptor());
}
}
所以现在的问题是我想要一个特定的 header 配置+不同客户端的resttemplate的通用 header 配置。我还可以看到模式会重复,也许我需要一个抽象的“Client”类。
您认为我必须如何进行设计才能使其优雅并按预期工作?
非常感谢您的帮助。
最佳答案
我想你已经快到了。首先看一下RestTemplateBuilder
您在上面使用的。您可能希望根据通用模板“构建”客户端。
在您的配置中,创建通用模板Builder
:
@Configuration
public RestClientConfig {
private static final String HOST = "http://example.com/service/";
// Here you can define a common builder for all of your RestTemplates
@Bean
public RestTemplateBuilder restTemplateBuilder() {
// Here you're appending the interceptors to the common template
return new RestTemplateBuilder().addAdditionalInterceptors(
new AddHeadersRequestInterceptor(),
new LogRequestInterceptor()
).rootUri(HOST);
}
@Bean
public RestTemplate shifuRestTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder.addAdditionalInterceptors(new CustomShifuHeaderIntercepter()
// Add other Customizers or MessageConverters here with #additionalCustomizers and #additionalMessageConverters...
.build();
}
public RestTemplate foobarRestTemplate(RestTemplateBuilder restTemplateBuilder) {
...
}
}
然后根据需要将它们注入(inject)到您的@Services/@Components
中。您仍然可以在此处使用您的 Client
服务理念,但您可以注入(inject)您已配置的模板。希望有帮助。
关于java - 使用 RestTemplate 和 RestTemplateCustomizer 与多个服务的正确架构是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52321516/