RestTemplate實踐

hatch發表於2018-04-08

RestTemplate是Spring提供的用於訪問Rest服務的客戶端,RestTemplate提供了多種便捷訪問遠端Http服務的方法,能夠大大提高客戶端的編寫效率。

ClientHttpRequestFactory

RestTemplate可以通過使用ClientHttpRequestFactory指定不同的HTTP請求方式。

ClientHttpRequestFactory介面主要提供了兩種實現方式:

  • SimpleClientHttpRequestFactory,使用J2SE提供的方式(既java.net包提供的方式)建立底層的Http請求連線。

  • HttpComponentsClientHttpRequestFactory方式,底層使用HttpClient訪問遠端的Http服務,使用HttpClient可以配置連線池和證照等資訊。

HttpComponentsClientHttpRequestFactory方式

HttpClient配置連線池

@Component("httpClientFactory")
public class HttpClientFactoryBean extends DefaultConnectionKeepAliveStrategy implements FactoryBean<HttpClient>,
    Runnable, InitializingBean, DisposableBean{
/**
 * 保持最多的連線數
 */
private static final int CONNECTION_MAX_TOTAL = 50;

/**
 * domain最多連線數
 */
private static final int CONNECTION_MAX_ROUTE = 10;

/**
 * 空閒時間
 */
private static final int IDLE_TIMEOUT = 30 * 1000;

private ScheduledExecutorService service;

private PoolingHttpClientConnectionManager connectionManager;

private HttpClient httpClient;

@Override
public HttpClient getObject(){

    HttpClientBuilder builder = HttpClients.custom();

    builder.setKeepAliveStrategy(this);
    builder.setConnectionManager(connectionManager);

    httpClient = builder.build();

    return httpClient;
}

@Override
public void afterPropertiesSet(){
    service = new ScheduledThreadPoolExecutor(1, new ThreadFactoryBuilder().setNameFormat("httpclient-%d").build());
    service.scheduleWithFixedDelay(this, 60, 60, TimeUnit.SECONDS);

    connectionManager = new PoolingHttpClientConnectionManager();

    connectionManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(10 * 1000).build());
    connectionManager.setDefaultConnectionConfig(ConnectionConfig.custom().setBufferSize(8 * 1024)
            .setFragmentSizeHint(8 * 1024).build());
    connectionManager.setMaxTotal(CONNECTION_MAX_TOTAL);
    connectionManager.setDefaultMaxPerRoute(CONNECTION_MAX_ROUTE);

}

@Override
public void destroy() {
    service.shutdownNow();
    connectionManager.close();
}

@Override
public Class<HttpClient> getObjectType() {
    return HttpClient.class;
}

@Override
public boolean isSingleton() {
    return true;
}

@Override
public void run() {

    if (connectionManager == null) {
        return;

    }
    connectionManager.closeExpiredConnections();
    connectionManager.closeIdleConnections(IDLE_TIMEOUT, TimeUnit.SECONDS);

}
複製程式碼

}

配置RestTemplate

@Component
public class RestRequest extends RestTemplate {

@Autowired
@Qualifier("httpClientFactory")
private HttpClientFactoryBean httpClientFactory;

@PostConstruct
public void init() throws Exception {

	HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClientFactory.getObject());

	setRequestFactory(factory);

	List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
	converters.add(new FastJsonHttpMessageConverter4());

	setMessageConverters(converters);

	setErrorHandler(new ResponseErrorHandler());

}
複製程式碼

}

相關文章