一个客户端实例能够呗通过相应RestClientBuilder创建,通过调用RestClient#builder(HttpHost...)静态方法创建。
创建的参数要求仅仅是客户端需要用于交互的一个或多个httpHost,提供httpHost实例如下代码
RestClient restClient = RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http")).build();
RestClient是线程安全的并且根使用它的应用有相同的生命周期,这是重要的当不需要的时候去关闭它用来是所有的被他使用的资源被合理释放
就像隐含的http client instance 和他的线程:
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.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);
设置节点选择器被用于过滤节点,客户端将会发送请求到他们(他们已经被设置到客户端自身)中的一个,
这是有用的对于实例来说当嗅探生效的时候去阻止发送请求到专用的master节点,默认情况下客户端发送到所有的节点
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);
}
});
设置一个回调它允许去修改默认的请求配置
比如 (request timeouts, authentication, or anything that the org.apache.http.client.config.RequestConfig.Builder allows to set)
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 client 配置 比如( encrypted communication over ssl, or anything that the org.apache.http.impl.nio.client.HttpAsyncClientBuilder allows to set)