Elasticsearch整理匯總-RestHighLevelClient使用JAVA(二)
聲明:所有內容均為本人查找網上資料匯總整理,非本人原創,但有本人整理心得;感謝每位學習愛好者對知識的傳承和分享!!!
Java REST Client 有兩種風格:
Java Low Level REST Client :用于Elasticsearch的官方低級客戶端。它允許通過http與Elasticsearch集群通信。將請求編排和響應反編排留給用戶自己處理。它兼容所有的Elasticsearch版本。(PS:學過WebService的話,對編排與反編排這個概念應該不陌生。可以理解為對請求參數的封裝,以及對響應結果的解析)
Java High Level REST Client :用于Elasticsearch的官方高級客戶端。它是基于低級客戶端的,它提供很多API,并負責請求的編排與響應的反編排。(PS:就好比是,一個是傳自己拼接好的字符串,并且自己解析返回的結果;而另一個是傳對象,返回的結果也已經封裝好了,直接是對象,更加規范了參數的名稱以及格式,更加面對對象一點)
項目依賴:
POM文件
<dependencies>
<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-high-level-client -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.10.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>aliyun</id>
<url>https://repo1.maven.org/maven2/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
JAVA代碼配置客戶端:
import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import cn.com.taiji.common.pub.StringTools; @Configuration public class ElasticsearchConfig { @Value("#{esProperties.hostIp}") private String hostIp; @Value("#{esProperties.hostPort}") private int hostPort; @Value("#{esProperties.userName}") private String userName; @Value("#{esProperties.password}") private String password; @Bean public RestHighLevelClient restHighLevelClient() { String[] hosts = this.hostIp.split(";"); HttpHost[] httpHosts = new HttpHost[hosts.length]; for(int i=0;i<hosts.length;i++) { httpHosts[i] = new HttpHost(hosts[i], hostPort, "http"); } RestClientBuilder builder = RestClient.builder(httpHosts); if(StringTools.hasText(userName)){ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password)); builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider)); } RestHighLevelClient client = new RestHighLevelClient(builder); return client; } }
主要參考博客:http://www.rzrgm.cn/cjsblog/p/10232581.html

浙公網安備 33010602011771號