Java 将RestTemplate和RestTemplateCustomizer与多个服务一起使用的正确架构是什么?
你好吗?我希望你做得很棒 我正在为我的公司创建一个新的Spring Boot应用程序,对于这个特定的应用程序,我需要与不同的微服务进行通信,有些微服务具有不同的配置。例如:某些服务需要不同的头 我不太清楚如何以正确优雅的方式做这件事。我采用的方法是将“客户机”创建为@Component,使用如下创建的rest模板与微服务进行通信:Java 将RestTemplate和RestTemplateCustomizer与多个服务一起使用的正确架构是什么?,java,spring,oop,spring-boot,architecture,Java,Spring,Oop,Spring Boot,Architecture,你好吗?我希望你做得很棒 我正在为我的公司创建一个新的Spring Boot应用程序,对于这个特定的应用程序,我需要与不同的微服务进行通信,有些微服务具有不同的配置。例如:某些服务需要不同的头 我不太清楚如何以正确优雅的方式做这件事。我采用的方法是将“客户机”创建为@Component,使用如下创建的rest模板与微服务进行通信: @Component public class ShifuClient { private final RestTemplate restTemplate;
@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,它添加公共头并记录请求
/**
* 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());
}
}
所以现在的问题是,我需要一个特定的头配置+不同客户机的resttemplate的公共头配置。我还可以看到模式会重复,也许我需要一个抽象的“客户机”类
你认为我必须如何进行设计,使其优雅,并使其按预期工作
非常感谢你的帮助。我想你就快到了。首先,看一看您在上面使用的。您可能希望基于通用模板“构建”客户机 在您的配置中,使通用模板
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) {
...
}
}
然后根据需要将它们注入到您的
@Services/@组件中。您仍然可以在这里使用客户机
服务理念,但您可以插入已配置的模板。希望有帮助。谢谢你的帮助。实际上,对于设置RestTemplateBuilder的部分,您无法接收RestTemplateBuilder,因为它表示存在循环依赖关系。我想你必须创建一个新的RestTemplateBuilder。刚刚编辑过。没有机会进行测试,但如果您喜欢这种方法,通常情况下会是这样