Elasticsearch Java Low Level REST Client(初始化)

博弈發表於2019-01-19

初始化

可以通過相應的RestClientBuilder類構建RestClient例項,通過RestClient#builder(HttpHost...)靜態方法建立,唯一必需的引數是客戶端將與之通訊的一個或多個主機,作為HttpHost的例項提供,如下所示:

RestClient restClient = RestClient.builder(
        new HttpHost("localhost", 9200, "http"),
        new HttpHost("localhost", 9201, "http")).build();

RestClient類是執行緒安全的,理想情況下與使用它的應用程式具有相同的生命週期,重要的是不再需要時關閉它,以便它所使用的所有資源得到正確釋放,以及底層的http客戶端例項及其執行緒:

restClient.close();

RestClientBuilder還允許在構建RestClient例項時可選地設定以下配置引數:

RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
Header[] defaultHeaders = new Header[]{new BasicHeader("header", "value")};
builder.setDefaultHeaders(defaultHeaders);

設定需要隨每個請求一起傳送的預設headers,以防止必須為每個請求指定它們。

RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
builder.setMaxRetryTimeoutMillis(10000);

設定在多次嘗試同一請求時應該遵守的超時,預設值為30秒,與預設socket超時相同。如果自定義socket超時,則應相應地調整最大重試超時。

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

設定用於過濾節點的節點選擇器,客戶端將傳送請求到設定給客戶端本身的節點之一,這有助於防止在啟用嗅探時向專用主節點傳送請求,預設情況下,客戶端向每個配置的節點傳送請求。

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允許設定的任何內容)。

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允許設定的任何內容)。


上一篇:Java Low Level REST Client 入門

下一篇:執行請求

相關文章