将RestTemplae和RestTemplateCustomizer与多种服务一起使用的正确结构是什么?

时间:2018-09-13 20:40:28

标签: java spring oop spring-boot architecture

你好吗?我希望你做的很棒。

我正在为公司创建一个新的Spring Boot应用程序,对于这个特定的应用程序,我需要与不同的微服务(某些具有不同的配置)进行通信。例如:某些服务需要不同的标题。

我不太确定如何以正确的优雅方式进行操作。我采用的方法是将@Client创建为“客户端”,并使用如下创建的rest模板与微服务通信:

@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的通用标头配置。我还可以看到模式会重复,也许我需要一个抽象的“ Client”类。

您认为我应该如何进行设计才能使外观优雅并按预期进行这项工作?

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我认为您快到了。首先,看看上面使用的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) {
          ...
    }

}

然后根据需要将它们注入您的@Services/@Components中。您仍然可以在此处使用Client服务理念,但是可以注入已配置的模板。希望有帮助。