初始化
编辑初始化
编辑可以通过相应的 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);
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); } });
设置一个回调,该回调允许修改默认的请求配置(例如,请求超时、身份验证,或 |
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 进行加密通信,或 |