Java High Level REST Client
Java High Level REST Client 至少需要Java 1.8,它的主要目标是封装Elasticsearch REST API 提供易于编写的代码实现。
脚手架
git@github.com:nasuyun/example-springboot.git
cd example-springboot
vi ./src/main/resources/application.properties # 替换成你的应用用户名密码
mvn clean package
java -jar ./target/example-springboot-0.0.1.jar
依赖
- maven 依赖
pom.xml
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.8.23</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.8.23</version>
</dependency>
- gradle 依赖
build.gradle
dependencies {
compile 'org.elasticsearch:elasticsearch:6.8.23'
compile 'org.elasticsearch.client:elasticsearch-rest-high-level-client:6.8.23'
}
初始化客户端
首选 我们需要创建一个 RestHighLevelClient 实例,然后使用该实例进行索引的增删改查操作。
final String server = "https://router.nasuyun.com:9200";
final String username = "your_app_username";
final String password = "your_app_password";
// 构建ES客户端
RestHighLevelClient client() {
Header[] headers = new Header[]{new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")};
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
RestClientBuilder builder = RestClient.builder(HttpHost.create(server))
.setDefaultHeaders(headers)
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
return new RestHighLevelClient(builder);
}
正确的关闭客户端
在使用RestHighLevelClient进行相关操作后,我们需要根据场景正确的调用client.close()
释放它的资源。
- 低频场景 例如创建索引、删除索引、修改mapping等元数据操作, 应采用
用完即释放
的方式。
try (RestHighLevelClient client = client()) {
// 操作
client.dosomething ...
} catch (Exception e) {
log.error("", e);
}
// try-with-resource 自动调用 client.clsoe()释放
- 高频场景 例如持续高并发的写入或查询索引,应采用
连接复用
的方式
final RestHighLevelClient client;
// 在构造阶段创建RestHighLevelClient实例
Operator() {
client = client();
}
void write() {
bulk by client ...
}
void search() {
search by client ...
}
// 当业务应用关闭时调用close
void close() {
client.close();
}
tip
高频场景:应避免频繁创建client导致socket端口耗尽。