查看官方文档
地址:https://www.elastic.co/guide/index.html
找到Elasticsearch Clients
,点进去
里面有各种语言的客户端,推荐Java REST Client
,Java原生APIJava API
高级客户端是对低级客户端的封装,在Getting started中能依次看到兼容性、API文档、Maven依赖等介绍。
官方文档上写的依赖
初始化
SpringBoot项目集成ES
访问https://start.spring.io/,添加依赖时搜索elastic
,会出现ES相关依赖。
生成的springboot项目中:
<!--Elasticsearch相关依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
如有必要,在pom.xml文件中自己定义ES版本依赖,保证和本地版本一致。
配置类
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));
return client;
}
}
或者在application.yml中配置
查看ES相关源码
虽然这里导入了三个类,但都是静态内部类,核心类就一个:ElasticsearchRestClientConfigurations
package org.springframework.boot.autoconfigure.elasticsearch;
import ...
/**
* Elasticsearch rest client infrastructure configurations.
*/
class ElasticsearchRestClientConfigurations {
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(RestClientBuilder.class)
static class RestClientBuilderConfiguration {
//RestClientBuilder
@Bean
RestClientBuilder elasticsearchRestClientBuilder(
ElasticsearchRestClientProperties properties,
ObjectProvider<RestClientBuilderCustomizer> builderCustomizers) {
HttpHost[] hosts = properties.getUris().stream()
.map(this::createHttpHost).toArray(HttpHost[]::new);
RestClientBuilder builder = RestClient.builder(hosts);
//...
return builder;
}
//...
}
@Configuration(proxyBeanMethods