ElasticSearch整合SpringBoot搭建配置的方法是什么

其他教程   发布日期:2023年06月28日   浏览次数:452

本文小编为大家详细介绍“ElasticSearch整合SpringBoot搭建配置的方法是什么”,内容详细,步骤清晰,细节处理妥当,希望这篇“ElasticSearch整合SpringBoot搭建配置的方法是什么”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

    项目搭建

    老规矩,先建

    1. maven
    项目,下面是我的
    1. pom.xml
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    5. <modelVersion>4.0.0</modelVersion>
    6. <groupId>org.example</groupId>
    7. <artifactId>springboot-es-all</artifactId>
    8. <version>1.0-SNAPSHOT</version>
    9. <properties>
    10. <java.version>1.8</java.version>
    11. </properties>
    12. <parent>
    13. <groupId>org.springframework.boot</groupId>
    14. <artifactId>spring-boot-starter-parent</artifactId>
    15. <version>2.1.3.RELEASE</version>
    16. </parent>
    17. <dependencies>
    18. <!--test-->
    19. <dependency>
    20. <groupId>org.springframework.boot</groupId>
    21. <artifactId>spring-boot-starter-test</artifactId>
    22. </dependency>
    23. <!--ElasticSearch 客户端依赖-->
    24. <dependency>
    25. <groupId>org.elasticsearch.client</groupId>
    26. <artifactId>elasticsearch-rest-client</artifactId>
    27. <version>7.8.0</version>
    28. </dependency>
    29. <dependency>
    30. <groupId>org.elasticsearch</groupId>
    31. <artifactId>elasticsearch</artifactId>
    32. <version>7.8.0</version>
    33. </dependency>
    34. <dependency>
    35. <groupId>org.elasticsearch.client</groupId>
    36. <artifactId>elasticsearch-rest-high-level-client</artifactId>
    37. <version>7.8.0</version>
    38. </dependency>
    39. <!--Hutool依赖-->
    40. <dependency>
    41. <groupId>cn.hutool</groupId>
    42. <artifactId>hutool-all</artifactId>
    43. <version>5.8.4</version>
    44. </dependency>
    45. <!--fast-json-->
    46. <dependency>
    47. <groupId>com.alibaba</groupId>
    48. <artifactId>fastjson</artifactId>
    49. <version>1.2.58</version>
    50. </dependency>
    51. <dependency>
    52. <groupId> org.slf4j </groupId>
    53. <artifactId> slf4j-api </artifactId>
    54. <version> 1.6.4 </version>
    55. </dependency>
    56. <dependency>
    57. <groupId>org.slf4j</groupId>
    58. <artifactId>slf4j-simple</artifactId>
    59. <version>1.7.25</version>
    60. <scope>compile</scope>
    61. </dependency>
    62. <dependency>
    63. <groupId>org.projectlombok</groupId>
    64. <artifactId>lombok</artifactId>
    65. </dependency>
    66. </dependencies>
    67. <build>
    68. <plugins>
    69. <plugin>
    70. <groupId>org.springframework.boot</groupId>
    71. <artifactId>spring-boot-maven-plugin</artifactId>
    72. <version>2.1.3.RELEASE</version>
    73. </plugin>
    74. </plugins>
    75. </build>
    76. </project>

    这里我使用的是

    1. elasticsearch-rest-high-level-client
    官方客户端,建议大家尽量用官方的,因为随着
    1. es
    的不断升级,很多
    1. api
    都过时了,如果你使用
    1. spring-boot-starter-data-elasticsearch
    这个要依赖社区去维护,很多新特性你没法使用到,也会存在安全性问题。

    配置客户端

    启动类:

    1. @SpringBootApplication
    2. public class EsStudyApplication {
    3. public static void main(String[] args) {
    4. SpringApplication.run(EsStudyApplication.class, args);
    5. }
    6. }

    配置文件

    1. application.yml
    :
    1. server:
    2. port: 9000
    3. elasticsearch:
    4. host: 0.0.0.0
    5. port: 9200
    6. username:
    7. password:

    客户端配置

    1. config.EsClientConfig
    :
    1. @Configuration
    2. public class EsClientConfig {
    3. @Value("${elasticsearch.host}")
    4. private String host;
    5. @Value("${elasticsearch.port}")
    6. private int port;
    7. @Value("${elasticsearch.username}")
    8. private String userName;
    9. @Value("${elasticsearch.password}")
    10. private String password;
    11. @Bean
    12. public RestHighLevelClient restHighLevelClient() {
    13. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    14. credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
    15. RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
    16. RestClient.builder(new HttpHost( host, port, "http")).setHttpClientConfigCallback(httpClientBuilder -&gt; {
    17. httpClientBuilder.setMaxConnTotal(500);
    18. httpClientBuilder.setMaxConnPerRoute(300);
    19. return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    20. })
    21. );
    22. return restHighLevelClient;
    23. }
    24. }

    然后客户端我们就配好了,客户端的配置其实还有很多,感兴趣的同学自行查阅。后续使用的时候,直接导入

    1. RestHighLevelClient
    实例就好了

    接着启动它,如果控制没有报错,说明配置没啥问题了, 记得要开启

    1. es
    服务~

    索引API初探 & Index API

    下面我们写一点测试用例,来验证我们是否可以操作

    1. es
    ,为了方便演示,这里直接使用
    1. SpringBootTest
    来测试,大家平时在写
    1. springboot
    项目,类测试的时候也可以这么做

    ping

    新建

    1. api.IndexApi
    ,调用
    1. ping()
    方法来测试是否链接成功:
    1. @Slf4j
    2. @SpringBootTest
    3. public class IndexApi {
    4. /**
    5. * es 索引
    6. */
    7. public static final String index = "study";
    8. @Autowired
    9. private RestHighLevelClient client;
    10. @Test
    11. public void ping() throws IOException {
    12. if(client.ping(RequestOptions.DEFAULT)) {
    13. log.info("链接成功");
    14. }else {
    15. log.info("链接失败 !");
    16. }
    17. }
    18. }

    点击

    1. IndexApi
    左上角的绿色箭头启动测试用例, 如果报错,尝试添加以下 注解
    1. @RunWith(SpringRunner.class)
    2. @SpringBootTest(classes = { EsStudyApplication.class })
    3. public class IndexApi {....}

    返回:

    链接成功

    说明

    1. 客户端
    1. es
    服务端是通的

    创建索引 & create

    通过前面的学习,有了一定的基础之后,回到代码中其实就是调调

    1. 方法
    ,因为你知道了这个代码的逻辑做了什么操作。下面来看下如何创建索引:
    1. /**
    2. * 创建索引
    3. */
    4. @Test
    5. public void createIndex() throws IOException {
    6. CreateIndexRequest request = new CreateIndexRequest(index);
    7. CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
    8. log.info("创建索引 ===> "+ JSONObject.toJSONString(createIndexResponse)); // 创建索引 ===> {"acknowledged":true,"fragment":false,"shardsAcknowledged":true}
    9. }

    大家可以返回到

    1. kibana
    中查看
    1. 索引
    是否被创建,从而验证代码执行是否成功

    添加别名:

    1. // alias
    2. request.alias(new Alias("study_alias"));

    索引设置

    1. settings
    :
    1. // index settings
    2. request.settings(
    3. Settings.builder()
    4. .put("index.number_of_shards", 3)
    5. .put("index.number_of_replicas", 2)
    6. );

    索引映射

    1. mapping
    :
    1. // index mappings
    2. // {
    3. // "mapping": {
    4. // "_doc": {
    5. // "properties": {
    6. // "name": {
    7. // "type": "text"
    8. // }
    9. // }
    10. // }
    11. // }
    12. // }
    13. XContentBuilder builder = XContentFactory.jsonBuilder();
    14. builder.startObject();
    15. {
    16. builder.startObject("properties");
    17. {
    18. builder.startObject("name");
    19. {
    20. builder.field("type", "text");
    21. }
    22. builder.endObject();
    23. }
    24. builder.endObject();
    25. }
    26. builder.endObject();
    27. request.mapping(builder);

    设置请求超时时间:

    1. // 请求设置
    2. request.setTimeout(TimeValue.timeValueMinutes(1));

    索引是否存在 & exist

    1. /**
    2. * 判断索引是否存在
    3. * @throws IOException
    4. */
    5. @Test
    6. public void existIndex() throws IOException {
    7. GetIndexRequest request = new GetIndexRequest(index);
    8. boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
    9. log.info("索引{}存在 ===> {}", index, exists);
    10. }

    删除索引

    1. /**
    2. * 删除索引
    3. * @throws IOException
    4. */
    5. @Test
    6. public void delIndex() throws IOException {
    7. DeleteIndexRequest request = new DeleteIndexRequest(index);
    8. AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
    9. log.info("删除索引 ===> {}", JSONObject.toJSONString(delete)); // 删除索引 ===> {"acknowledged":true,"fragment":false}
    10. }

    以上就是ElasticSearch整合SpringBoot搭建配置的方法是什么的详细内容,更多关于ElasticSearch整合SpringBoot搭建配置的方法是什么的资料请关注九品源码其它相关文章!