三.SpringBoot整合Elasticsearch

前言

我们整合es直接给es发请求就可以了,但是现在有很多方式去调用es的接口,那都有那些呢?

一.java调用es的方式和工具

访问es端口 访问方式 使用工具 缺点
9300 TCP transport-api.jar 不适配es版本,es 8.0之后弃用。
9200 HTTP JestClient 非官方,对应es版本更新慢。
9200 HTTP RestTemplate 模拟发送http请求,但是很多请求需要自己封装。
9200 HTTP HttpClient 模拟发送http请求,但是很多请求需要自己封装。
9200 HTTP Elasticsearch-Rest-Client 官方RestClient,封装了es的操作,API层次分明,上手简单。

二.java集成Elasticsearch-Rest-Client

Elasticsearch-Rest-Client官方文档

1.引入pom

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.3.1</version>
</dependency>

2.导入版本不一致问题

比如你想导入 7.3.1版本的,但是你导入之后发现不是7.3.1版本的。
原因: 因为springboot默认对Elasticsearch版本进行了引入。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3.编写配置类

@Configuration
public class EsConfig {
    
    
	
	//发送请求时的请求设置项(全局通用)
    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();
    }
	
	//注入
    @Bean
    public RestHighLevelClient config(){
    
    
        RestClientBuilder builder = null;
        //es的ip、访问的端口号、网络协议
        builder = RestClient.builder(new HttpHost("127.0.0.1",9200,"http"));
        RestHighLevelClient client = new RestHighLevelClient(builder);
        return client;
    }
}

4.测试类

@SpringBootTest
@RunWith(SpringRunner.class)
public class test {
    
    

    @Autowired
    RestHighLevelClient restClient;

	//测试从java保存数据到es
    @Test
    public void testEs() throws IOException {
    
    
       IndexRequest indexRequest = new IndexRequest("ikun");
        indexRequest.id("1");
        Kunkun kunkun = new Kunkun();
        kunkun.setJineng("唱跳rap篮球");
        kunkun.setName("小black子");
        //把对象转为json字符串
        String s = JSON.toJSONString(kunkun);
        //保存的数据
        indexRequest.source(s, XContentType.JSON);
        //执行保存的操作(同步操作,文档里面有写异步请求)
        IndexResponse index = restClient.index(indexRequest, EsConfig.COMMON_OPTIONS);
    }

    @Data
    class Kunkun {
    
    
        private String jineng;
        private String name;
    }
}

4.1 执行前

在这里插入图片描述

4.2 执行后

在这里插入图片描述

5.其他篇章

一.Elasticsearch快速入门及使用

二.Elasticsearch进阶

猜你喜欢

转载自blog.csdn.net/twotwo22222/article/details/131463595