初始化

编辑

一个 RestClient 实例可以通过相应的 RestClientBuilder 类构建,该类可以通过 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); 

设置需要与每个请求一起发送的默认标头,以避免必须为每个请求指定它们。

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 HttpClientConfigCallback() {
        @Override
        public HttpAsyncClientBuilder customizeHttpClient(
                HttpAsyncClientBuilder httpClientBuilder) {
            return httpClientBuilder.setProxy(
                new HttpHost("proxy", 9000, "http"));  
        }
    });

设置一个回调,允许修改 http 客户端配置(例如通过 ssl 进行加密通信,或 org.apache.http.impl.nio.client.HttpAsyncClientBuilder 允许设置的任何内容)