ElasticSearch Low Level Rest Client
Initialization(初始化)
A RestClient instance can be built through the corresponding RestClientBuilder class, created via RestClient#builder(HttpHost...) static method. The only required argument is one or more hosts that the client will communicate with, provided as instances of HttpHost as follows:
// RestClient實例可以通過相應(yīng)的RestClientBuilder類構(gòu)建,該類是通過RestClient#builder(HttpHost…)靜態(tài)方法創(chuàng)建的。唯一需要的參數(shù)是客戶機將與之通信的一個或多個主機,作為HttpHost的實例提供如下:
RestClient restClient = RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http")).build();
The RestClient class is thread-safe and ideally has the same lifecycle as the application that uses it. It is important that it gets closed when no longer needed so that all the resources used by it get properly released, as well as the underlying http client instance and its threads:
// RestClient類是線程安全的,并且理想情況下具有與使用它的應(yīng)用程序相同的生命周期。重要的是,當(dāng)不再需要它的時候,它會被關(guān)閉,這樣它所使用的所有資源,以及底層http客戶端實例和它的線程都會被正確釋放:
restClient.close();
RestClientBuilder also allows to optionally set the following configuration parameters while building the RestClient instance:
// RestClientBuilder還允許在構(gòu)建RestClient實例時選擇性地設(shè)置以下配置參數(shù):
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200, "http"));
Header[] defaultHeaders = new Header[]{new BasicHeader("header", "value")};
// 設(shè)置每個請求需要發(fā)送的默認(rèn)頭文件,以避免必須在每個請求中指定它們
builder.setDefaultHeaders(defaultHeaders);
// Set the default headers that need to be sent with each request, to prevent having to specify them with each single request
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200, "http"));
builder.setFailureListener(new RestClient.FailureListener() {
@Override
public void onFailure(Node node) {
// 設(shè)置一個偵聽器,在需要采取操作時,每當(dāng)節(jié)點發(fā)生故障時,偵聽器都會收到通知。啟用故障嗅探時在內(nèi)部使用。
}
});
// Set a listener that gets notified every time a node fails, in case actions need to be taken. Used internally when sniffing on failure is enabled.
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200, "http"));
// 將節(jié)點選擇器設(shè)置為用于過濾客戶機將發(fā)送請求到的節(jié)點之間的節(jié)點,這些節(jié)點被設(shè)置為客戶機本身。這對于防止在啟用嗅探時將請求發(fā)送到專用的主節(jié)點非常有用。默認(rèn)情況下,客戶機向每個配置的節(jié)點發(fā)送請求。
builder.setNodeSelector(NodeSelector.SKIP_DEDICATED_MASTERS);
// Set the node selector to be used to filter the nodes the client will send requests to among the ones that are set to the client itself. This is useful for instance to prevent sending requests to dedicated master nodes when sniffing is enabled. By default the client sends requests to every configured node.
Set a callback that allows to modify the default request configuration (e.g. request timeouts, authentication, or anything that the org.apache.http.client.config.RequestConfig.Builderallows to set)
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200, "http"));
builder.setRequestConfigCallback(
new RestClientBuilder.RequestConfigCallback() {
@Override
public RequestConfig.Builder customizeRequestConfig(
RequestConfig.Builder requestConfigBuilder) {
// 設(shè)置一個回調(diào)函數(shù),允許修改默認(rèn)的請求配置(例如,請求超時、身份驗證或org.apache.http.client.config.RequestConfig中的任何內(nèi)容)。生成器允許設(shè)置)
return requestConfigBuilder.setSocketTimeout(10000);
}
});
Set a callback that allows to modify the http client configuration (e.g. encrypted communication over ssl, or anything that the org.apache.http.impl.nio.client.HttpAsyncClientBuilder 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(
// 設(shè)置一個回調(diào),允許修改http客戶機配置(例如,通過ssl或org.apache.http.impl.nio.client的任何加密通信)。HttpAsyncClientBuilder允許設(shè)置)
new HttpHost("proxy", 9000, "http"));
}
});
Performing requests(執(zhí)行請求)
一旦RestClinet被創(chuàng)建, 請求可以通過調(diào)用發(fā)送performRequest或performRequestAsync. performRequest是同步的, 將阻塞調(diào)用線程并Response在請求成功時返回, 如果失敗則拋出異常. performRequestAsync是異步的, 并接受一個ResponseListenere參數(shù), 它Response在請求成功時或Exception if it4失敗時調(diào)用
// This is synchronous:
Request request = new Request("GET", /);
Response response = restClient.performRequest(request);
// 解釋
new Request("GET", "/");
param one: The HTTP method(GET, POST, HEAD, etc); (這是HTTP方法)
param two: The endpoint on the server; (服務(wù)器上的端點, 等于就是請求方法)
// And this is asynchronous:
Request request = new Request("GET", "/");
restClient.performRequestAsync(request, new ResponseListener(){
@Override
public void onSuccess(Response response) {
// Handle the response(處理相應(yīng))
}
@Override
public void onFailure(Exception exception) {
// Handle the failure(處理失敗)
}
});
// 解釋
new Request("GET", "/");
param one: The HTTP method(GET, POST, HEAD, etc); (這是HTTP方法)
param two: The endpoint on the server; (服務(wù)器上的端點, 等于就是請求方法)
You can add request parameters to the request object:(您可以向請求對象添加請求參數(shù):)
request.addParameter("pretty", "true");
You can set the body of the request to any HttpEntity:(您可以將請求的主體設(shè)置為任何Http實體)
request.setEntity(new NStringEntity("{\"json\":\"text\"}", ContentType.APPLICATION_JSON));
Warning: The ContentType specified for the HttpEntity is important because it will be used to set the Content-Type header so that Elasticsearch can properly parse the content.
您可以將請求的主體設(shè)置為任何HttpEntity:
為HttpEntity指定的ContentType非常重要,因為它將用于設(shè)置content - type頭部,以便Elasticsearch能夠正確解析內(nèi)容。
You can also set it to a String which will default to a ContentType of application/json
// 您還可以將其設(shè)置為一個字符串,該字符串將默認(rèn)為application/json的ContentType。
request.setJsonEntity("{\"json\":\"text\"}");
Request Options (請求設(shè)置)
The RequestOptions class holds parts of the request that should be shared between many requests in the same application. You can make a singleton instance and share it between all requests
// RequestOptions類包含請求的一些部分,這些部分應(yīng)該在同一個應(yīng)用程序中的多個請求之間共享。你可以創(chuàng)建一個單實例,并在所有請求之間共享
private static final RequestOptions COMMON_OPTIONS;
static {
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
// Add any headers needed by all requests.
// 添加所有請求所需的任何頭。
builder.addHeader("Authorization", "Bearer " + TOKEN);
// 定制響應(yīng)使用者 Customize the response consumer.
builder.setHttpAsyncResponseConsumerFactory(
new HttpAsyncResponseConsumerFactory
.HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));
COMMON_OPTIONS = builder.build();
}
// addHeader is for headers that are required for authorization or to work with a proxy in front of Elasticsearch. There is no need to set the Content-Type header because the client will automatically set that from the HttpEntity attached to the request.
// You can set the NodeSelector which controls which nodes will receive requests. NodeSelector.NOT_MASTER_ONLY is a good choice.
// You can also customize the response consumer used to buffer the asynchronous responses. The default consumer will buffer up to 100MB of response on the JVM heap. If the response is larger then the request will fail. You could, for example, lower the maximum size which might be useful if you are running in a heap constrained environment like the example above.
// Once you’ve created the singleton you can use it when making requests:
// addHeader適用于授權(quán)或在Elasticsearch前使用代理所需的標(biāo)頭。無需設(shè)置Content-Type 標(biāo)頭,因為客戶端會自動將其設(shè)置為HttpEntity 附加到請求。
// 您可以設(shè)置NodeSelector控制哪些節(jié)點將接收請求。NodeSelector.NOT_MASTER_ONLY是個不錯的選擇。
// 您還可以自定義用于緩沖異步響應(yīng)的響應(yīng)使用者。默認(rèn)使用者將在JVM堆上緩沖最多100MB的響應(yīng)。如果響應(yīng)較大,則請求將失敗。例如,如果您在如上例所示的堆約束環(huán)境中運行,則可以降低可能有用的最大大小。
// 創(chuàng)建單例后,您可以在發(fā)出請求時使用它:
request.setOptions(COMMON_OPTIONS);
// You can also customize these options on a per request basis. For example, this adds an extra header:
// 您還可以根據(jù)請求自定義這些選項。例如,這會添加一個額外的標(biāo)頭:
RequestOptions.Builder options = COMMON_OPTIONS.toBuilder();
options.addHeader("cats", "knock things off of other things");
request.setOptions(options);
Multiple parallel asynchronous actions(多個并行異步操作)
// The client is quite happy to execute many actions in parallel. The following example indexes many documents in parallel. In a real world scenario you’d probably want to use the _bulk API instead, but the example is illustrative.
// 客戶端很樂意并行執(zhí)行許多操作。下面的示例并行索引許多文檔。在真實的場景中,您可能想要使用_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) {
// Process the returned response 處理返回的響應(yīng)
latch.countDown();
}
@Override
public void onFailure(Exception exception) {
// Handle the returned exception, due to communication error or a response with status code that indicates an error 處理返回的異常,由于通信錯誤或響應(yīng)狀態(tài)代碼指示錯誤
latch.countDown();
}
}
);
}
latch.await();
Logging(日志)
The Java REST client uses the same logging library that the Apache Async Http Client uses: Apache Commons Logging, which comes with support for a number of popular logging implementations. The java packages to enable logging for are org.elasticsearch.client for the client itself and org.elasticsearch.client.sniffer for the sniffer.
The request tracer logging can also be enabled to log every request and corresponding response in curl format. That comes handy when debugging, for instance in case a request needs to be manually executed to check whether it still yields the same response as it did. Enable trace logging for the tracerpackage to have such log lines printed out. Do note that this type of logging is expensive and should not be enabled at all times in production environments, but rather temporarily used only when needed.
Java REST客戶端使用與Apache Async Http Client使用的相同的日志庫:Apache Commons Logging,它支持許多流行的日志記錄實現(xiàn)。啟用日志記錄的java包org.elasticsearch.client用于客戶端本身和org.elasticsearch.client.sniffer嗅探器。
還可以啟用請求跟蹤器日志記錄,以便以curl格式記錄每個請求和相應(yīng)的響應(yīng)。這在調(diào)試時很方便,例如,如果需要手動執(zhí)行請求以檢查它是否仍然產(chǎn)生與它相同的響應(yīng)。啟用tracer 程序包的跟蹤日志記錄以打印出此類日志行。請注意,此類日志記錄非常昂貴,不應(yīng)在生產(chǎn)環(huán)境中始終啟用,而應(yīng)僅在需要時暫時使用。
Common configuration(默認(rèn)配置)
As explained in Initialization, the RestClientBuilder supports providing both a RequestConfigCallback and an HttpClientConfigCallback which allow for any customization that the Apache Async Http Client exposes. Those callbacks make it possible to modify some specific behaviour of the client without overriding every other default configuration that the RestClient is initialized with. This section describes some common scenarios that require additional configuration for the low-level Java REST Client.
如初始化中所述,RestClientBuilder 支持提供a RequestConfigCallback和HttpClientConfigCallback 允許Apache Async Http Client公開的任何自定義。這些回調(diào)可以修改客戶端的某些特定行為,而不會覆蓋RestClient 初始化的所有其他默認(rèn)配置。本節(jié)介紹一些需要為低級Java REST Client進(jìn)行其他配置的常見方案。
TimeOut(超時)
Configuring requests timeouts can be done by providing an instance ofRequestConfigCallback while building the RestClient through its builder. The interface has one method that receives an instance oforg.apache.http.client.config.RequestConfig.Builder as an argument and has the same return type. The request config builder can be modified and then returned. In the following example we increase the connect timeout (defaults to 1 second) and the socket timeout (defaults to 30 seconds).
配置請求超時可以通過提供RequestConfigCallback構(gòu)建RestClient通過其構(gòu)建器的實例來完成 。該接口有一個方法,它接收一個org.apache.http.client.config.RequestConfig.Builder 作為參數(shù)的實例 并具有相同的返回類型??梢孕薷恼埱笈渲脴?gòu)建器,然后返回。在以下示例中,我們將連接超時(默認(rèn)為1秒)和套接字超時(默認(rèn)為30秒)增加。
RestClientBuilder builder = RestClient.builder(
new HttpHost(“l(fā)ocalhost”,9200))。
setRequestConfigCallback(
new RestClientBuilder.RequestConfigCallback(){
@ Override
public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder
requestConfigBuilder){
return requestConfigBuilder
.setConnectTimeout(5000)
.setSocketTimeout (60000);
}
});
Number of Threads(線程數(shù))
The Apache Http Async Client starts by default one dispatcher thread, and a number of worker threads used by the connection manager, as many as the number of locally detected processors (depending on whatRuntime.getRuntime().availableProcessors() returns). The number of threads can be modified as follows:
Apache Http Async Client默認(rèn)啟動一個調(diào)度程序線程,以及連接管理器使用的許多工作線程,與本地檢測到的處理器數(shù)量一樣多(取決于 Runtime.getRuntime().availableProcessors()返回的內(nèi)容)。線程數(shù)可以修改如下:
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200))
.setHttpClientConfigCallback(new HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder.setDefaultIOReactorConfig(
IOReactorConfig.custom()
.setIoThreadCount(1)
.build());
}
});
Basic authentication
Configuring basic authentication can be done by providing anHttpClientConfigCallback while building the RestClient through its builder. The interface has one method that receives an instance oforg.apache.http.impl.nio.client.HttpAsyncClientBuilder as an argument and has the same return type. The http client builder can be modified and then returned. In the following example we set a default credentials provider that requires basic authentication.
配置基本身份驗證可以通過提供一段 HttpClientConfigCallback時間來構(gòu)建RestClient它的構(gòu)建器來完成。該接口有一個方法,它接收一個org.apache.http.impl.nio.client.HttpAsyncClientBuilder 作為參數(shù)的實例 并具有相同的返回類型??梢孕薷膆ttp客戶端構(gòu)建器,然后返回。在以下示例中,我們設(shè)置了需要基本身份驗證的默認(rèn)憑據(jù)提供程序。
final CredentialsProvider credentialsProvider =
new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("user", "password"));
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200))
.setHttpClientConfigCallback(new HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder
.setDefaultCredentialsProvider(credentialsProvider);
}
});
Preemptive Authentication can be disabled, which means that every request will be sent without authorization headers to see if it is accepted and, upon receiving an HTTP 401 response, it will resend the exact same request with the basic authentication header. If you wish to do this, then you can do so by disabling it via the HttpAsyncClientBuilder:
可以禁用搶占式身份驗證,這意味著每個請求都將在沒有授權(quán)頭的情況下發(fā)送,以查看它是否被接受,并且在接收到HTTP 401響應(yīng)后,它將使用基本身份驗證頭重新發(fā)送完全相同的請求。如果你想這樣做,你可以通過HttpAsyncClientBuilder禁用它:
final CredentialsProvider credentialsProvider =
new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("user", "password"));
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200))
.setHttpClientConfigCallback(new HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
httpClientBuilder.disableAuthCaching();
return httpClientBuilder
.setDefaultCredentialsProvider(credentialsProvider);
}
});
Encrypted communication(加密通信)
Encrypted communication can also be configured through theHttpClientConfigCallback. Theorg.apache.http.impl.nio.client.HttpAsyncClientBuilder received as an argument exposes multiple methods to configure encrypted communication: setSSLContext, setSSLSessionStrategy and setConnectionManager, in order of precedence from the least important. The following is an example:
加密通信也可以通過 HttpClientConfigCallback。的 org.apache.http.impl.nio.client.HttpAsyncClientBuilder :作為一個參數(shù)暴露多種方法來配置加密通信接收setSSLContext,setSSLSessionStrategy并且 setConnectionManager,從最不重要的優(yōu)先級順序。以下是一個例子:
KeyStore truststore = KeyStore.getInstance("jks");
try (InputStream is = Files.newInputStream(keyStorePath)) {
truststore.load(is, keyStorePass.toCharArray());
}
SSLContextBuilder sslBuilder = SSLContexts.custom()
.loadTrustMaterial(truststore, null);
final SSLContext sslContext = sslBuilder.build();
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200, "https"))
.setHttpClientConfigCallback(new HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder.setSSLContext(sslContext);
}
});
If no explicit configuration is provided, the system default configuration will be used.
如果未提供顯式配置,則將使用系統(tǒng)默認(rèn)配置 。
Other(其他)
For any other required configuration needed, the Apache HttpAsyncClient docs should be consulted: https://hc.apache.org/httpcomponents-asyncclient-4.1.x/ .
對于所需的任何其他所需配置,應(yīng)參考Apache HttpAsyncClient文檔:https://hc.apache.org/httpcomponents-asyncclient-4.1.x/ 。
If your application runs under the security manager you might be subject to the JVM default policies of caching positive hostname resolutions indefinitely and negative hostname resolutions for ten seconds. If the resolved addresses of the hosts to which you are connecting the client to vary with time then you might want to modify the default JVM behavior. These can be modified by addingnetworkaddress.cache.ttl= andnetworkaddress.cache.negative.ttl= to your Java security policy.
如果您的應(yīng)用程序在安全管理器下運行,則可能會受到JVM默認(rèn)策略的限制,即無限期緩存正主機名解析和負(fù)主機名解析,持續(xù)10秒。如果您連接客戶端的主機的已解析地址隨時間變化,那么您可能希望修改默認(rèn)的JVM行為。這些可以通過添加修改 networkaddress.cache.ttl=<timeout> ,并 networkaddress.cache.negative.ttl=<timeout> 在您的 Java安全策略。
Node selector(節(jié)點選擇)
The client sends each request to one of the configured nodes in round-robin fashion. Nodes can optionally be filtered through a node selector that needs to be provided when initializing the client. This is useful when sniffing is enabled, in case only dedicated master nodes should be hit by HTTP requests. For each request the client will run the eventually configured node selector to filter the node candidates, then select the next one in the list out of the remaining ones.
客戶端以循環(huán)方式將每個請求發(fā)送到其中一個配置的節(jié)點??梢赃x擇通過在初始化客戶端時需要提供的節(jié)點選擇器來過濾節(jié)點。這在啟用嗅探時很有用,以防只有HTTP請求才能訪問專用主節(jié)點。對于每個請求,客戶端將運行最終配置的節(jié)點選擇器以過濾候選節(jié)點,然后從列表中選擇下一個節(jié)點選擇器。
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200, "http"));
// Set an allocation aware node selector that allows to pick a node in the local rack if any available, otherwise go to any other node in any rack. It acts as a preference rather than a strict requirement, given that it goes to another rack if none of the local nodes are available, rather than returning no nodes in such case which would make the client forcibly revive a local node whenever none of the nodes from the preferred rack is available.
// 設(shè)置一個分配感知節(jié)點選擇器,允許在本地機架中選擇可用的節(jié)點,否則轉(zhuǎn)到機架中的任何其他節(jié)點。它作為一個偏好,而不是一個嚴(yán)格的要求,鑒于它到另一架如果沒有一個本地節(jié)點可用,而不是返回沒有節(jié)點在這種情況下這將使客戶端強制重啟本地節(jié)點時沒有一個節(jié)點從首選架是可用的。
builder.setNodeSelector(new NodeSelector() {
@Override
public void select(Iterable<Node> nodes) {
/*
* Prefer any node that belongs to rack_one. If none is around(選擇屬于rack_one的任何節(jié)點。如果周圍沒有)
* we will go to another rack till it's time to try and revive(我們將去另一個機架,直到時間來嘗試和恢復(fù))
* some of the nodes that belong to rack_one.(屬于rack_one的一些節(jié)點。)
*/
boolean foundOne = false;
for (Node node : nodes) {
String rackId = node.getAttributes().get("rack_id").get(0);
if ("rack_one".equals(rackId)) {
foundOne = true;
break;
}
}
if (foundOne) {
Iterator<Node> nodesIt = nodes.iterator();
while (nodesIt.hasNext()) {
Node node = nodesIt.next();
String rackId = node.getAttributes().get("rack_id").get(0);
if ("rack_one".equals(rackId) == false) {
nodesIt.remove();
}
}
}
}
});
warning
Node selectors that do not consistently select the same set of nodes will make round-robin behaviour unpredictable and possibly unfair. The preference example above is fine as it reasons about availability of nodes which already affects the predictability of round-robin. Node selection should not depend on other external factors or round-robin will not work properly.
不一致地選擇相同節(jié)點集的節(jié)點選擇器將使循環(huán)行為變得不可預(yù)測并且可能不公平。上面的偏好示例很好,因為它可以解釋已經(jīng)影響循環(huán)可預(yù)測性的節(jié)點的可用性。節(jié)點選擇不應(yīng)該依賴于其他外部因素,否則循環(huán)將無法正常工作。
Sniffer (嗅探器)
Minimal library that allows to automatically discover nodes from a running Elasticsearch cluster and set them to an existing RestClient instance. It retrieves by default the nodes that belong to the cluster using the Nodes Info api and uses jackson to parse the obtained json response.
Compatible with Elasticsearch 2.x and onwards.
最小的庫,允許從正在運行的Elasticsearch集群中自動發(fā)現(xiàn)節(jié)點并將它們設(shè)置為現(xiàn)有RestClient實例。它默認(rèn)使用節(jié)點信息api檢索屬于集群的節(jié)點,并使用jackson解析獲得的json響應(yīng)。
與Elasticsearch 2.x及以后版本兼容。
JavaDoc
The javadoc for the REST client sniffer can be found at <a>https://artifacts.elastic.co/javadoc/org/elasticsearch/client/elasticsearch-rest-client-sniffer/7.0.0/index.html</a>.
可以在https://artifacts.elastic.co/javadoc/org/elasticsearch/client/elasticsearch-rest-client-sniffer/7.0.0/index.html找到REST客戶端嗅探器的javadoc 。
Maven Repository(maven倉庫)
The REST client sniffer is subject to the same release cycle as Elasticsearch. Replace the version with the desired sniffer version, first released with 5.0.0-alpha4. There is no relation between the sniffer version and the Elasticsearch version that the client can communicate with. Sniffer supports fetching the nodes list from Elasticsearch 2.x and onwards.
If you are looking for a SNAPSHOT version, the Elastic Maven Snapshot repository is available at https://snapshots.elastic.co/maven/.
REST客戶端嗅探器與Elasticsearch具有相同的發(fā)布周期。用所需的嗅探器版本替換版本,首先發(fā)布5.0.0-alpha4。嗅探器版本與客戶端可以與之通信的Elasticsearch版本之間沒有任何關(guān)系。Sniffer支持從Elasticsearch 2.x及以后獲取節(jié)點列表。
如果您正在尋找SNAPSHOT版本,可以訪問https://snapshots.elastic.co/maven/獲取Elastic Maven Snapshot存儲庫。
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client-sniffer</artifactId>
<version>7.0.0</version>
</dependency>
Gradle配置
dependencies {
compile 'org.elasticsearch.client:elasticsearch-rest-client-sniffer:7.0.0'
}
Usage(用法)
Once a RestClient instance has been created as shown in Initialization, a Sniffer can be associated to it. The Sniffer will make use of the provided RestClient to periodically (every 5 minutes by default) fetch the list of current nodes from the cluster and update them by calling RestClient#setNodes.
一旦RestClient創(chuàng)建了一個實例,如初始化中所示,Sniffer就可以將其關(guān)聯(lián)到它。在Sniffer將利用所提供的RestClient 定期(每5分鐘默認(rèn)情況下)獲取從集群當(dāng)前節(jié)點列表,并通過調(diào)用更新它們RestClient#setNodes。
RestClient restClient = RestClient.builder(
new HttpHost("localhost", 9200, "http"))
.build();
Sniffer sniffer = Sniffer.builder(restClient).build();
It is important to close the Sniffer so that its background thread gets properly shutdown and all of its resources are released. The Sniffer object should have the same lifecycle as the RestClient and get closed right before the client:
關(guān)閉它以Sniffer使其后臺線程正確關(guān)閉并釋放其所有資源非常重要。該Sniffer 對象應(yīng)具有與RestClient客戶端相同的生命周期并在客戶端之前關(guān)閉:
sniffer.close();
restClient.close();
The Sniffer updates the nodes by default every 5 minutes. This interval can be customized by providing it (in milliseconds) as follows:
該Sniffer更新默認(rèn)情況下,每5分鐘的節(jié)點。可以通過提供(以毫秒為單位)來定制此間隔,如下所示:
RestClient restClient = RestClient.builder(
new HttpHost("localhost", 9200, "http"))
.build();
Sniffer sniffer = Sniffer.builder(restClient)
.setSniffIntervalMillis(60000).build();
It is also possible to enable sniffing on failure, meaning that after each failure the nodes list gets updated straightaway rather than at the following ordinary sniffing round. In this case a SniffOnFailureListener needs to be created at first and provided at RestClient creation. Also once the Sniffer is later created, it needs to be associated with that same SniffOnFailureListenerinstance, which will be notified at each failure and use the Sniffer to perform the additional sniffing round as described.
也可以在失敗時啟用嗅探,這意味著在每次失敗之后,節(jié)點列表會立即更新,而不是在接下來的普通嗅探輪次中。在這種情況下,SniffOnFailureListener需要首先創(chuàng)建并在RestClient創(chuàng)建時提供。此外,一旦 Sniffer稍后創(chuàng)建,它需要與同一個SniffOnFailureListener實例相關(guān)聯(lián),該 實例將在每次失敗時得到通知,并使用它Sniffer來執(zhí)行所述的額外嗅探輪。
SniffOnFailureListener sniffOnFailureListener =
new SniffOnFailureListener();
RestClient restClient = RestClient.builder(
// 將失敗偵聽器設(shè)置為RestClient實例
new HttpHost("localhost", 9200))
.setFailureListener(sniffOnFailureListener)
.build();
// 在嗅探失敗時,不僅節(jié)點在每次失敗后都會更新,而且在失敗后的一分鐘內(nèi),還會比平時更快地安排額外的嗅探輪,假設(shè)事情會恢復(fù)正常并且我們想要檢測到盡快地??梢許niffer通過該setSniffAfterFailureDelayMillis 方法在創(chuàng)建時定制所述間隔。請注意,如上所述,如果未啟用嗅探失敗,則此最后一個配置參數(shù)無效。就是3無效
Sniffer sniffer = Sniffer.builder(restClient)
.setSniffAfterFailureDelayMillis(30000)
.build();
// 將Sniffer實例設(shè)置為失敗偵聽器
sniffOnFailureListener.setSniffer(sniffer);
The Elasticsearch Nodes Info api doesn’t return the protocol to use when connecting to the nodes but only their host:port key-pair, hence http is used by default. In case https should be used instead, the ElasticsearchNodesSniffer instance has to be manually created and provided as follows:
Elasticsearch Nodes Info api不會返回連接到節(jié)點時使用的協(xié)議,而只返回它們的host:port密鑰對,因此http 默認(rèn)使用。如果https應(yīng)該使用,則 ElasticsearchNodesSniffer必須手動創(chuàng)建實例并提供如下:
RestClient restClient = RestClient.builder(
new HttpHost("localhost", 9200, "http"))
.build();
NodesSniffer nodesSniffer = new ElasticsearchNodesSniffer(
restClient,
ElasticsearchNodesSniffer.DEFAULT_SNIFF_REQUEST_TIMEOUT,
ElasticsearchNodesSniffer.Scheme.HTTPS);
Sniffer sniffer = Sniffer.builder(restClient)
.setNodesSniffer(nodesSniffer).build();
In the same way it is also possible to customize the sniffRequestTimeout, which defaults to one second. That is the timeout parameter provided as a querystring parameter when calling the Nodes Info api, so that when the timeout expires on the server side, a valid response is still returned although it may contain only a subset of the nodes that are part of the cluster, the ones that have responded until then.
以同樣的方式,也可以自定義sniffRequestTimeout,默認(rèn)為一秒。這是timeout在調(diào)用Nodes Info api時作為查詢字符串參數(shù)提供的參數(shù),因此當(dāng)服務(wù)器端超時到期時,仍會返回有效響應(yīng),盡管它可能只包含屬于集群的節(jié)點的子集,那些在那之前做出回應(yīng)的人。
RestClient restClient = RestClient.builder(
new HttpHost("localhost", 9200, "http"))
.build();
NodesSniffer nodesSniffer = new ElasticsearchNodesSniffer(
restClient,
TimeUnit.SECONDS.toMillis(5),
ElasticsearchNodesSniffer.Scheme.HTTP);
Sniffer sniffer = Sniffer.builder(restClient)
.setNodesSniffer(nodesSniffer).build();
Also, a custom NodesSniffer implementation can be provided for advanced use-cases that may require fetching the Nodes from external sources rather than from Elasticsearch:
此外,NodesSniffer可以為高級用例提供自定義實現(xiàn),這些用例可能需要從外部源而不是從Elasticsearch獲取`Node`s:
RestClient restClient = RestClient.builder(
new HttpHost("localhost", 9200, "http"))
.build();
NodesSniffer nodesSniffer = new NodesSniffer() {
@Override
public List<Node> sniff() throws IOException {
// Fetch the hosts from the external source
// 從外部源獲取主機
return null;
}
};
Sniffer sniffer = Sniffer.builder(restClient)
.setNodesSniffer(nodesSniffer).build();