当前位置:   article > 正文

ElasticSearch--Springboot整合ElasticSearch_gulimallelasticsearchconfig

gulimallelasticsearchconfig

【笔记于学习尚硅谷课程所作】

5、Springboot整合ElasticSearch

1.快速创建SpringBoot项目

2.导入依赖

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

<!--加入7.4.2的版本控制-->
<properties>
        <java.version>1.8</java.version>
        <elasticsearch.version>7.4.2</elasticsearch.version>
    </properties>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

3.创建配置文件GulimallElasticSearchConfig.java

//给容器中注入一个RestHighLevelClient
@Configuration
public class GulimallElasticSearchConfig {

        //通用配置项
    public  static  final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder =RequestOptions.DEFAULT.toBuilder();



        COMMON_OPTIONS = builder.build();
    }
    
    @Bean
    public RestHighLevelClient esRestClient() {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.196.128", 9200, "http")));

        return client;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

4.测试,在测试test中测试

@SpringBootTest
class GulimallSearchApplicationTests {

    @Autowired
    private RestHighLevelClient client;

    @Test
    void test(){
        System.out.println(client);
    }

    /**
     * 测试存储数据
     */
    @SneakyThrows
    @Test
    void test1 (){
        IndexRequest indexRequest = new IndexRequest("users");
        indexRequest.id("1");
        User user = new User();
        user.setName("li");
        user.setAge(18);
        String json = JSON.toJSONString(user);
        indexRequest.source(json, XContentType.JSON);

        IndexResponse index = client.index(indexRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

        System.out.println(index);
    }

    @Data
    class User{
        private  String name;
        private  Integer age;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/神奇cpp/article/detail/952165
推荐阅读
相关标签
  

闽ICP备14008679号