下面是使用配置類配置HttpClient
的示例。它通過這個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));
}
}
和示例application.yml
fake.username: test
fake.password: test
poolMaxTotal: 10
可以外化配置值,以你的application.yml
與poolMaxTotal
以上等。
要在每個環境中支持不同的值,可以使用Spring配置文件。使用上面的示例,您可以創建application-prod.yml
,其中poolMaxTotal
的「prod」特定值。然後使用--spring.profiles.active=prod
啓動您的應用程序,並使用「prod」值代替application.yml
中的默認值。無論您需要多少環境,都可以做到這一點。
application-prod.yml
poolMaxTotal: 20
對於異步HttpClient
,在這裏看到:http://vincentdevillers.blogspot.fr/2013/10/a-best-spring-asyncresttemplate.html
值得稱道的典範(其實有點類似於我做了什麼),但仍從什麼Dropwizard有很遠。 –