一旦建立了RestClient
,就能够经过调用performRequest
或performRequestAsync
来发送请求,performRequest
是同步的,将阻塞调用线程并在请求成功时返回Response
,若是失败则抛出异常。performRequestAsync
是异步的,它接受一个ResponseListener
参数,它在请求成功时调用Response
,若是失败则调用Exception
。json
这是同步的:segmentfault
Request request = new Request( "GET", "/"); Response response = restClient.performRequest(request);
GET
,POST
,HEAD
等)。这是异步的:服务器
Request request = new Request( "GET", "/"); restClient.performRequestAsync(request, new ResponseListener() { @Override public void onSuccess(Response response) { } @Override public void onFailure(Exception exception) { } });
onSuccess
方法:处理响应。onFailure
:处理失败。你能够将请求参数添加到请求对象:app
request.addParameter("pretty", "true");
你能够将请求的body设置为任何HttpEntity
:异步
request.setEntity(new NStringEntity( "{\"json\":\"text\"}", ContentType.APPLICATION_JSON));
为HttpEntity
指定的ContentType
很重要,由于它将用于设置Content-Type
header,以便Elasticsearch能够正确解析内容。
你还能够将其设置为String
,默认为ContentType
为application/json
。ide
request.setJsonEntity("{\"json\":\"text\"}");
RequestOptions
类保存应在同一应用程序中的多个请求之间共享的部分请求,你能够建立单例实例并在全部请求之间共享它:post
private static final RequestOptions COMMON_OPTIONS; static { RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder(); builder.addHeader("Authorization", "Bearer " + TOKEN); builder.setHttpAsyncResponseConsumerFactory( new HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024)); COMMON_OPTIONS = builder.build(); }
builder.addHeader
:添加全部请求所需的任何header。builder.setHttpAsyncResponseConsumerFactory
:自定义响应消费者。addHeader
用于受权或在Elasticsearch前使用代理所需的header,无需设置Content-Type
header,由于客户端将自动从附加到请求的HttpEntity
设置该header。ui
你能够设置NodeSelector
来控制哪些节点将接收请求。线程
NodeSelector.NOT_MASTER_ONLY
是一个不错的选择。代理
你还能够自定义用于缓冲异步响应的响应消费者,默认消费者将在JVM堆上缓冲最多100MB的响应,若是响应较大,则请求将失败。例如,若是你在堆约束环境(如上面的例子)中运行,则能够下降可能有用的最大大小。
建立单例后,你能够在发出请求时使用它:
request.setOptions(COMMON_OPTIONS);
你还能够根据请求自定义这些选项,例如,这会添加额外的header:
RequestOptions.Builder options = COMMON_OPTIONS.toBuilder(); options.addHeader("cats", "knock things off of other things"); request.setOptions(options);
客户端很乐意并行执行许多操做,如下示例并行索引许多文档,在现实世界的场景中,你可能但愿使用_bulk
API,但示例是做例证的。
final CountDownLatch latch = new CountDownLatch(documents.length); for (int i = 0; i < documents.length; i++) { Request request = new Request("PUT", "/posts/doc/" + i); //let's assume that the documents are stored in an HttpEntity array request.setEntity(documents[i]); restClient.performRequestAsync( request, new ResponseListener() { @Override public void onSuccess(Response response) { latch.countDown(); } @Override public void onFailure(Exception exception) { latch.countDown(); } } ); } latch.await();
onSuccess
:处理返回的响应。onFailure
:因为通讯错误或带有指示错误的状态码的响应,处理返回的异常。