概述
Java操作elasticSearch整合SpringBoot
针对elasticSearch不同端口操作客户端API:
1)、9300:TCP (es集群通讯9300)
· spring-data-elasticsearch:transport-api.jar;
· springboot 版本不同, transport-api.jar 不同,不能适配 es 版本
· 官网 es的版本:7.x 已经不建议使用,8 以后就要废弃
2)、9200:HTTP
· JestClient:非官方,更新慢
· RestTemplate:模拟发 HTTP 请求,ES 很多操作需要自己封装,麻烦
· HttpClient:同上 ▷ 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
▷Elasticsearch-Rest-Client(elasticsearch-rest-high-level-client)
整合SpringBoot
版本说明:elasticSearch版本 kibana版本 Elasticsearch-Rest-Client版本 请保持一致
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.2</version>
</dependency>
配置: 容器中导入RestHighLevelClient 操作以及加密鉴权
**
* 1.导入依赖
* 2.容器中导入RestHighLevelClient 操作9200
*/
//注解配置启动容器自动执行
@Configuration
public class ElasticSearchConfig {
//常亮配置项 在调用es操作的时候直接引用这个常量
public static final RequestOptions COMMON_OPTIONS;
static {
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
//加密内容
// builder.addHeader("Authorization","Bearer"+TOKEN );
// builder.setHttpAsyncResponseConsumerFactory(
// new HttpAsyncResponseConsumerFactory
// .HeapBufferedResponseConsumerFactory(30*1024*1024*1024)
// );
COMMON_OPTIONS = builder.build();
}
//容器中引入client 调用es服务时,用这个client请求
@Bean
public RestHighLevelClient esRestClient(){
//多个es的写法
// RestHighLevelClient client = new RestHighLevelClient(
// RestClient.builder(
// //多个es new HttpHost("192.168.31.120",9200,"http"),
// new HttpHost("192.168.31.125",9200,"http")));
// return client;
RestClientBuilder builder = null;
builder = RestClient.builder(new HttpHost("192.168.31.125",9200,"http"));
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
}
单元测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class GulimallSearchApplicationTests {
@Autowired
private RestHighLevelClient client;
@Test
public void contextLoads() {
System.out.println(client);
}
}
2021-11-05 15:44:39.332 INFO 2108 --- [ main] c.a.g.s.GulimallSearchApplicationTests : Started GulimallSearchApplicationTests in 19.746 seconds (JVM running for 21.598)
org.elasticsearch.client.RestHighLevelClient@342e690b
2021-11-05 15:44:39.690 INFO 2108 --- [ Thread-9] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
Process finished with exit code 0
看到client的打印信息:org.elasticsearch.client.RestHighLevelClient@342e690b
整合成功
最后
以上就是犹豫冬瓜为你收集整理的springboot elasticsearch整合 (整合es操作)的全部内容,希望文章能够帮你解决springboot elasticsearch整合 (整合es操作)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复