且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-01-19 09:38:12

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

Below is an example of configuring a HttpClient with a configuration class. It configures basic authentication for all requests through this RestTemplate as well as some tweaks to the pool.

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));
  }
}

和示例application.yml

fake.username: test
fake.password: test
poolMaxTotal: 10

您可以像上面的poolMaxTotal等那样将配置值外部化到您的application.yml.

You can externalise configuration values to your application.yml as with poolMaxTotal etc. above.

要在每个环境中支持不同的值,可以使用Spring概要文件.使用上面的示例,您可以使用poolMaxTotal的特定"prod"值创建application-prod.yml.然后使用--spring.profiles.active=prod启动您的应用,并且将使用"prod"值代替application.yml中的默认值.您可以针对所需的许多环境执行此操作.

To support different values per environment you can use Spring profiles. Using the example above, you could just create application-prod.yml with a "prod" specific value for poolMaxTotal. Then start your app with --spring.profiles.active=prod and the "prod" value will be used instead of your default value in application.yml. You can do this for however many environments you need.

application-prod.yml

poolMaxTotal: 20

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

For an async HttpClient, see here: http://vincentdevillers.blogspot.fr/2013/10/a-best-spring-asyncresttemplate.html