能夠經過相應的RestClientBuilder
類構建RestClient
實例,經過RestClient#builder(HttpHost...)
靜態方法建立,惟一必需的參數是客戶端將與之通訊的一個或多個主機,做爲HttpHost的實例提供,以下所示:html
RestClient restClient = RestClient.builder( new HttpHost("localhost", 9200, "http"), new HttpHost("localhost", 9201, "http")).build();
RestClient
類是線程安全的,理想狀況下與使用它的應用程序具備相同的生命週期,重要的是再也不須要時關閉它,以便它所使用的全部資源獲得正確釋放,以及底層的http客戶端實例及其線程:node
restClient.close();
RestClientBuilder
還容許在構建RestClient
實例時可選地設置如下配置參數:apache
RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http")); Header[] defaultHeaders = new Header[]{new BasicHeader("header", "value")}; builder.setDefaultHeaders(defaultHeaders);
設置須要隨每一個請求一塊兒發送的默認headers,以防止必須爲每一個請求指定它們。segmentfault
RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http")); builder.setMaxRetryTimeoutMillis(10000);
設置在屢次嘗試同一請求時應該遵照的超時,默認值爲30秒,與默認socket超時相同。若是自定義socket超時,則應相應地調整最大重試超時。api
RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http")); builder.setFailureListener(new RestClient.FailureListener() { @Override public void onFailure(Node node) { } });
設置一個監聽器,每次節點出現故障時都會收到通知,以防須要採起措施,當啓用故障嗅探時在內部使用。安全
RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http")); builder.setNodeSelector(NodeSelector.SKIP_DEDICATED_MASTERS);
設置用於過濾節點的節點選擇器,客戶端將發送請求到設置給客戶端自己的節點之一,這有助於防止在啓用嗅探時向專用主節點發送請求,默認狀況下,客戶端向每一個配置的節點發送請求。socket
RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http")); builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() { @Override public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) { return requestConfigBuilder.setSocketTimeout(10000); } });
設置容許修改默認請求配置的回調(例如請求超時,身份驗證或org.apache.http.client.config.RequestConfig.Builder容許設置的任何內容)。async
RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http")); builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) { return httpClientBuilder.setProxy(new HttpHost("proxy", 9000, "http")); } });
設置容許修改http客戶端配置的回調(例如經過ssl進行加密通訊,或者org.apache.http.impl.nio.client.HttpAsyncClientBuilder容許設置的任何內容)。ide