Elasticsearch Java Low Level REST Client(初始化)

初始化

可以通过相应的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 入门

下一篇:执行请求

相关推荐