Spring可配置,高性能,计量的http客户端实例

And*_*tto 4 configuration spring apache-httpcomponents dropwizard spring-boot

来自DropWizard我已经习惯了它的HttpClientConfiguration,我很困惑,在Spring Boot中,我找不到一些支持以类似的方式控制http客户端实例,例如RestTemplates.

要在生产中工作,底层客户端实现应该是高性能的(例如,非阻塞io,具有连接重用和池化).

然后我需要设置超时或身份验证,可能是度量收集,cookie设置,SSL证书设置.

以上所有内容都应该很容易设置为不同的实例,以便在不同的上下文中使用不同的实例(例如,对于服务X使用这些设置和此池,对于Y使用另一个池和设置),大多数参数应该通过环境设置 - 在生产/ qa /开发中具有不同值的特定属性.

有没有可以用于此目的的东西?

Don*_*ler 7

以下是HttpClient使用配置类配置a的示例.它通过此配置所有请求的基本身份验证RestTemplate以及对池​​的一些调整.

HttpClientConfiguration.java

@Configuration
public class HttpClientConfiguration {

  private static final Logger log = LoggerFactory.getLogger(HttpClientConfiguration.class);

  @Autowired
  private Environment environment;

  @Bean
  public ClientHttpRequestFactory httpRequestFactory() {
    return new HttpComponentsClientHttpRequestFactory(httpClient());
  }

  @Bean
  public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate(httpRequestFactory());
    restTemplate.setInterceptors(ImmutableList.of((request, body, execution) -> {
      byte[] token = Base64.encodeBase64((format("%s:%s", environment.getProperty("fake.username"), environment.getProperty("fake.password"))).getBytes());
      request.getHeaders().add("Authorization", format("Basic %s", new String(token)));

      return execution.execute(request, body);
    }));

    return restTemplate;
  }

  @Bean
  public HttpClient httpClient() {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();

    // Get the poolMaxTotal value from our application[-?].yml or default to 10 if not explicitly set
    connectionManager.setMaxTotal(environment.getProperty("poolMaxTotal", Integer.class, 10));

    return HttpClientBuilder
      .create()
      .setConnectionManager(connectionManager)
      .build();
  }

  /**
   * Just for demonstration
   */
  @PostConstruct
  public void debug() {
    log.info("Pool max total: {}", environment.getProperty("poolMaxTotal", Integer.class));
  }
}
Run Code Online (Sandbox Code Playgroud)

和一个例子 application.yml

fake.username: test
fake.password: test
poolMaxTotal: 10
Run Code Online (Sandbox Code Playgroud)

您可以将配置值外部application.yml化为poolMaxTotal上面的等.

要支持每个环境的不同值,可以使用Spring配置文件.使用上面的示例,您可以application-prod.yml使用"prod"特定值创建poolMaxTotal.然后启动你的应用程序,--spring.profiles.active=prod将使用"prod"值而不是你的默认值application.yml.您可以在需要的许多环境中执行此操作.

application-prod.yml

poolMaxTotal: 20
Run Code Online (Sandbox Code Playgroud)

有关异步HttpClient,请参阅此处:http://vincentdevillers.blogspot.fr/2013/10/a-best-spring-asyncresttemplate.html