1)、9300:TCP
spring-data-elasticsearch:transport-api.jar;
通过对9300端口建立一个长连接,但是因为springboot 版本不同, transport-api.jar 不同,不能适配 es 版本,并且7.x 已经不建议使用,8 以后就要废弃。
2)、9200:HTTP
- JestClient:非官方,更新慢RestTemplate:模拟发 HTTP 请求,ES 很多操作需要自己封装,麻烦HttpClient:同上其实因为我们直接对9200端口进行操作,只要能发http请求的都可以,还有其他的Okhttp等但是这样对于DSL很麻烦,所以放弃。
Elasticsearch-Rest-Client:官方 RestClient,封装了 ES 操作,API 层次分明,上手简单紧跟版本变化。
最终选择 Elasticsearch-Rest-Client(elasticsearch-rest-high-level-client)
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high.html
开始整合:
如果使用的es是7版本下的,可以创建项目时在Nosql中选中spring支持的es那个更加方便,本文不讨论该情况
- 首先根据文档,导入maven依赖
org.elasticsearch.client elasticsearch-rest-high-level-client7.4.2
文档中可以看到,依赖有low和High之分,我们导入的是高阶依赖。他们就像jdbc和Mybatis一样进一步封装罢了。
2.我们发现我们新建的项目springboot支持的是6.4.3版本(springboot版本是2.2.2,如果是2.6.x应该是支持到了7.1.x版本)
所以我们要在pom文件中自己指定修改一下支持版本
3.编写配置类
@Configuration
public class ElasticSearchCongfig {
@Bean
public RestHighLevelClient esRestClient() {
RestClientBuilder builder;
builder=RestClient.builder(new HttpHost("192.168.56.10", 9200, "http"));
RestHighLevelClient client= new RestHighLevelClient(builder);
return client;
}
//执行发送请求时需要带COMMON_OPTIONS
public static final RequestOptions COMMON_OPIONS;
static {
RequestOptions.Builder builder=RequestOptions.DEFAULT.toBuilder();
COMMON_OPIONS=builder.build();
}
}
到此就整合完毕,我们编写配置类看一下是否整合成功
@Autowired
RestHighLevelClient client;
@Test
public void contextLoads() {
System.out.println(client);
}
可以看到成功打印出对象,说明已经整合成功。



