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版本 请保持一致
配置: 容器中导入RestHighLevelClient *** 作以及加密鉴权org.elasticsearch.client elasticsearch-rest-high-level-client7.4.2
** * 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
整合成功
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)