人肉翻譯,非谷歌機翻,部分地方添加了我的的理解,並作了分割,若有錯誤請在評論指出。轉載請指明原連接,尊重我的勞動成果。node
High-Level-Rest-Client基於Low-Level-Rest-Client封裝,Client配置方面基於Low-Level,而API使用上基於High-Level。apache
翻譯的版本爲6.5.4版本的Elasticsearch,部分不重要的內容(如Maven/Gradle座標、License等不在本文出現)。編程
在實際的配置過程當中,查看源碼發現LowLevelClient徹底基於HttpAsyncClient來實現的,內部具體組裝Client的細節,若是有時間會寫另一篇博文分享出來。json
1 RestClient restClient = RestClient.builder( 2 new HttpHost("localhost", 9200, "http"), 3 new HttpHost("localhost", 9201, "http")).build();
1 restClient.close();
1 RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http")); 2 Header[] defaultHeaders = new Header[]{new BasicHeader("header", "value")}; 3 builder.setDefaultHeaders(defaultHeaders);
1 RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http")); 2 builder.setMaxRetryTimeoutMillis(10000);
1 RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http")); 2 builder.setFailureListener(new RestClient.FailureListener() { 3 @Override 4 public void onFailure(Node node) { 5 6 } 7 });
1 RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http")); 2 builder.setNodeSelector(NodeSelector.SKIP_DEDICATED_MASTERS);
1 RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http")); 2 builder.setRequestConfigCallback( 3 new RestClientBuilder.RequestConfigCallback() { 4 @Override 5 public RequestConfig.Builder customizeRequestConfig( 6 RequestConfig.Builder requestConfigBuilder) { 7 return requestConfigBuilder.setSocketTimeout(10000); 8 } 9 });
1 RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http")); 2 builder.setHttpClientConfigCallback(new HttpClientConfigCallback() { 3 @Override 4 public HttpAsyncClientBuilder customizeHttpClient( 5 HttpAsyncClientBuilder httpClientBuilder) { 6 return httpClientBuilder.setProxy( 7 new HttpHost("proxy", 9000, "http")); 8 } 9 });
1 Request request = new Request( 2 "GET", //HTTP方法,支持GET、POST、HEAD等 3 "/"); //es服務端點endpoint 4 Response response = restClient.performRequest(request);
1 Request request = new Request( 2 "GET", //HTTP方法,支持GET、POST、HEAD等 3 "/"); //es服務端點endpoint 4 restClient.performRequestAsync(request, new ResponseListener() { 5 @Override 6 public void onSuccess(Response response) { 7 //成功回調 8 } 9 10 @Override 11 public void onFailure(Exception exception) { 12 //失敗回調 13 } 14 });
1 request.addParameter("pretty", "true");
若是將HttpEntity設置爲String,那麼ContentType會被默認設置爲application/json:api
1 private static final RequestOptions COMMON_OPTIONS; 2 static { 3 RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder(); 4 builder.addHeader("Authorization", "Bearer " + TOKEN); //設置請求頭的校驗信息 5 builder.setHttpAsyncResponseConsumerFactory( //設置Response的緩衝池大小 6 new HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024)); 7 COMMON_OPTIONS = builder.build(); 8 }
1 request.setOptions(COMMON_OPTIONS);
若是有某些請求須要對OPTIONS作必定程度的變動,能夠經過以下方式增量處理而不是從新寫一遍設置代碼:數組
1 RequestOptions.Builder options = COMMON_OPTIONS.toBuilder(); 2 options.addHeader("cats", "knock things off of other things"); 3 request.setOptions(options);
下面是一個使用閉鎖並行執行異步請求的例子。在實際的編程中,你通常會傾向於使用_bulk這個API來替代,固然了,下面的例子依然具備參考性:緩存
1 final CountDownLatch latch = new CountDownLatch(documents.length); 2 for (int i = 0; i < documents.length; i++) { 3 Request request = new Request("PUT", "/posts/doc/" + i); 4 //let's assume that the documents are stored in an HttpEntity array 5 request.setEntity(documents[i]); 6 restClient.performRequestAsync( 7 request, 8 new ResponseListener() { 9 @Override 10 public void onSuccess(Response response) { 11 12 latch.countDown(); 13 } 14 15 @Override 16 public void onFailure(Exception exception) { 17 18 latch.countDown(); 19 } 20 } 21 ); 22 } 23 latch.await();
1 Response response = restClient.performRequest(new Request("GET", "/")); 2 RequestLine requestLine = response.getRequestLine(); 3 HttpHost host = response.getHost(); 4 int statusCode = response.getStatusLine().getStatusCode(); 5 Header[] headers = response.getHeaders(); 6 String responseBody = EntityUtils.toString(response.getEntity());
1 RestClientBuilder builder = RestClient.builder( 2 new HttpHost("localhost", 9200)) 3 .setRequestConfigCallback( 4 new RestClientBuilder.RequestConfigCallback() { 5 @Override 6 public RequestConfig.Builder customizeRequestConfig( 7 RequestConfig.Builder requestConfigBuilder) { 8 return requestConfigBuilder 9 .setConnectTimeout(5000) //默認值1S 10 .setSocketTimeout(60000); //默認值30S 11 } 12 }) 13 .setMaxRetryTimeoutMillis(60000); //設置完SocketTimeout後,通常須要聯動修改這個值
1 RestClientBuilder builder = RestClient.builder( 2 new HttpHost("localhost", 9200)) 3 .setHttpClientConfigCallback(new HttpClientConfigCallback() { 4 @Override 5 public HttpAsyncClientBuilder customizeHttpClient( 6 HttpAsyncClientBuilder httpClientBuilder) { 7 return httpClientBuilder.setDefaultIOReactorConfig( 8 IOReactorConfig.custom() 9 .setIoThreadCount(1) 10 .build()); 11 } 12 });
1 final CredentialsProvider credentialsProvider = 2 new BasicCredentialsProvider(); 3 credentialsProvider.setCredentials(AuthScope.ANY, 4 new UsernamePasswordCredentials("user", "password")); 5 6 RestClientBuilder builder = RestClient.builder( 7 new HttpHost("localhost", 9200)) 8 .setHttpClientConfigCallback(new HttpClientConfigCallback() { 9 @Override 10 public HttpAsyncClientBuilder customizeHttpClient( 11 HttpAsyncClientBuilder httpClientBuilder) { 12 return httpClientBuilder 13 .setDefaultCredentialsProvider(credentialsProvider); 14 } 15 });
1 final CredentialsProvider credentialsProvider = 2 new BasicCredentialsProvider(); 3 credentialsProvider.setCredentials(AuthScope.ANY, 4 new UsernamePasswordCredentials("user", "password")); 5 6 RestClientBuilder builder = RestClient.builder( 7 new HttpHost("localhost", 9200)) 8 .setHttpClientConfigCallback(new HttpClientConfigCallback() { 9 @Override 10 public HttpAsyncClientBuilder customizeHttpClient( 11 HttpAsyncClientBuilder httpClientBuilder) { 12 httpClientBuilder.disableAuthCaching(); /* 禁用搶佔式身份驗證 */ 13 return httpClientBuilder 14 .setDefaultCredentialsProvider(credentialsProvider); 15 } 16 });
1 KeyStore truststore = KeyStore.getInstance("jks"); 2 try (InputStream is = Files.newInputStream(keyStorePath)) { 3 truststore.load(is, keyStorePass.toCharArray()); 4 } 5 SSLContextBuilder sslBuilder = SSLContexts.custom() 6 .loadTrustMaterial(truststore, null); 7 final SSLContext sslContext = sslBuilder.build(); 8 RestClientBuilder builder = RestClient.builder( 9 new HttpHost("localhost", 9200, "https")) 10 .setHttpClientConfigCallback(new HttpClientConfigCallback() { 11 @Override 12 public HttpAsyncClientBuilder customizeHttpClient( 13 HttpAsyncClientBuilder httpClientBuilder) { 14 return httpClientBuilder.setSSLContext(sslContext); 15 } 16 });
1 RestClientBuilder builder = RestClient.builder( 2 new HttpHost("localhost", 9200, "http")); 3 builder.setNodeSelector(new NodeSelector() { 4 @Override 5 public void select(Iterable<Node> nodes) { 6 /* 7 * Prefer any node that belongs to rack_one. If none is around 8 * we will go to another rack till it's time to try and revive 9 * some of the nodes that belong to rack_one. 10 */ 11 boolean foundOne = false; 12 for (Node node : nodes) { 13 String rackId = node.getAttributes().get("rack_id").get(0); 14 if ("rack_one".equals(rackId)) { 15 foundOne = true; 16 break; 17 } 18 } 19 if (foundOne) { 20 Iterator<Node> nodesIt = nodes.iterator(); 21 while (nodesIt.hasNext()) { 22 Node node = nodesIt.next(); 23 String rackId = node.getAttributes().get("rack_id").get(0); 24 if ("rack_one".equals(rackId) == false) { 25 nodesIt.remove(); 26 } 27 } 28 } 29 } 30 });
1 <dependency> 2 <groupId>org.elasticsearch.client</groupId> 3 <artifactId>elasticsearch-rest-client-sniffer</artifactId> 4 <version>6.5.4</version> 5 </dependency>
1 RestClient restClient = RestClient.builder( 2 new HttpHost("localhost", 9200, "http")) 3 .build(); 4 Sniffer sniffer = Sniffer.builder(restClient).build();
1 sniffer.close(); 2 restClient.close();
1 RestClient restClient = RestClient.builder( 2 new HttpHost("localhost", 9200, "http")) 3 .build(); 4 Sniffer sniffer = Sniffer.builder(restClient) 5 .setSniffIntervalMillis(60000).build(); //設置Sniffer刷新間隔
1 SniffOnFailureListener sniffOnFailureListener = 2 new SniffOnFailureListener(); //建立Sniffer失敗監聽器 3 RestClient restClient = RestClient.builder( 4 new HttpHost("localhost", 9200)) 5 .setFailureListener(sniffOnFailureListener) //爲RestClient設置監聽器 6 .build(); 7 Sniffer sniffer = Sniffer.builder(restClient) 8 .setSniffAfterFailureDelayMillis(30000) //設置失敗以後的額外調度延遲 9 .build(); 10 sniffOnFailureListener.setSniffer(sniffer); //爲監聽器設置Sniffer
1 RestClient restClient = RestClient.builder( 2 new HttpHost("localhost", 9200, "http")) 3 .build(); 4 NodesSniffer nodesSniffer = new ElasticsearchNodesSniffer( 5 restClient, 6 TimeUnit.SECONDS.toMillis(5), 7 ElasticsearchNodesSniffer.Scheme.HTTP); 8 Sniffer sniffer = Sniffer.builder(restClient) 9 .setNodesSniffer(nodesSniffer).build();
1 RestClient restClient = RestClient.builder( 2 new HttpHost("localhost", 9200, "http")) 3 .build(); 4 NodesSniffer nodesSniffer = new NodesSniffer() { 5 @Override 6 public List<Node> sniff() throws IOException { 7 return null; 8 } 9 }; 10 Sniffer sniffer = Sniffer.builder(restClient) 11 .setNodesSniffer(nodesSniffer).build();