Java Low Level REST Client 官网说明-客户端初始化

一个客户端实例能够呗通过相应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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值