官方文档地址:Initialization


    RestClient实例可以通过相应的RestClientBuilder类来构建,该类是通过RestClient#builder(HttpHost...)静态方法创建的。唯一需要的参数是客户端将与之通信的一个或多个主机,作为HttpHost的实例提供,如下所示:

    1. RestClient restClient = RestClient.builder(
    2. new HttpHost("localhost", 9200, "http"),
    3. 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);
    
    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) {
                //设置一个回调,允许修改默认的请求配置(例如,请求超时,认证,或任何 org.apache.http.client.config.RequestConfig.Builder 允许设置的内容)
                return requestConfigBuilder.setSocketTimeout(10000); 
            }
        });
    
    RestClientBuilder builder = RestClient.builder(
        new HttpHost("localhost", 9200, "http"));
    builder.setHttpClientConfigCallback(new HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(
                    HttpAsyncClientBuilder httpClientBuilder) {
                //设置一个允许修改 http 客户端配置的回调(例如,通过 ssl 加密通信,或任何 org.apache.http.impl.nio.client.HttpAsyncClientBuilder 允许设置的内容)
                return httpClientBuilder.setProxy(
                    new HttpHost("proxy", 9000, "http"));  
            }
        });