zoukankan      html  css  js  c++  java
  • SpringBoot整合Elasticsearch案例

    准备环境

    es环境,kibana环境,es-head环境

    ES数据准备

    使用kibaba造数据

    # 创建索引index

    PUT books

    GET books/_mapping
    

      

    PUT books/book/1
    {
      "id": {
        "type": 1
      },
      "bookName": {
        "type": "西游记"
      },
      "author": {
        "type": "吴承恩"
      }
    }
    PUT books/book/2
    {
      "id": {
        "type": 2
      },
      "bookName": {
        "type": "水浒传"
      },
      "author": {
        "type": "施耐庵"
      }
    }
    
    PUT books/book/3
    {
      "id": {
        "type": 3
      },
      "bookName": {
        "type": "三国演义"
      },
      "author": {
        "type": "罗贯中"
      }
    }
    
    PUT books/book/4
    {
      "id": {
        "type": 4
      },
      "bookName": {
        "type": "红楼梦"
      },
      "author": {
        "type": "曹雪芹"
      }
    }

    # 查询books的信息

    GET books/book/_search
    

     整合SpringBoot

     POM文件

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.6.RELEASE</version>
            <relativePath/>
        </parent>
        <groupId>com.estestcase</groupId>
        <artifactId>es-testcase</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>es-testcase</name>
        <description>ES-testcase project for Spring Boot</description>
        <properties>
            <java.version>1.8</java.version>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>elasticsearch-rest-high-level-client</artifactId>
                <version>7.9.1</version>
            </dependency>
            <dependency>
                <groupId>org.elasticsearch</groupId>
                <artifactId>elasticsearch</artifactId>
                <version>7.9.1</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.70</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <configuration>
                        <excludes>
                            <exclude>
                                <groupId>org.projectlombok</groupId>
                                <artifactId>lombok</artifactId>
                            </exclude>
                        </excludes>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>

    配置文件

    server.port=8080
    spring.application.name=es-testcase
    elasticSearch.host=192.168.2.101
    elasticSearch.port=9200
    elasticSearch.client.connectNum=10
    elasticSearch.client.connectPerRoute=50
    

    具体代码

    ESConfig

    package com.estestcase;
    
    import org.apache.http.HttpHost;
    import org.elasticsearch.client.RestClient;
    import org.elasticsearch.client.RestHighLevelClient;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Scope;
    
    @Configuration
    @ComponentScan(basePackageClasses = ESClientSpringFactory.class)
    public class ESConfig {
        @Value("${elasticSearch.host}")
        private String host;
    
        @Value("${elasticSearch.port}")
        private int port;
    
        @Value("${elasticSearch.client.connectNum}")
        private Integer connectNum;
    
        @Value("${elasticSearch.client.connectPerRoute}")
        private Integer connectPerRoute;
    
        @Bean
        public HttpHost httpHost() {
    
            return new HttpHost(host, port, "http");
        }
    
        @Bean(initMethod = "init", destroyMethod = "close")
        public ESClientSpringFactory getFactory() {
            return ESClientSpringFactory.
                    build(httpHost(), connectNum, connectPerRoute);
        }
    
        @Bean
        @Scope("singleton")
        public RestClient getRestClient() {
    
            return getFactory().getClient();
        }
    
        @Bean
        @Scope("singleton")
        public RestHighLevelClient getRHLClient() {
    
            return getFactory().getRhlClient();
        }
    }

    ESClientSpringFactory

    package com.estestcase;
    
    import lombok.extern.slf4j.Slf4j;
    import org.apache.http.HttpHost;
    import org.elasticsearch.client.RestClient;
    import org.elasticsearch.client.RestClientBuilder;
    import org.elasticsearch.client.RestHighLevelClient;
    
    import java.io.IOException;
    
    @Slf4j
    public class ESClientSpringFactory {
        public static int CONNECT_TIMEOUT_MILLIS = 1000;
        public static int SOCKET_TIMEOUT_MILLIS = 30000;
        public static int CONNECTION_REQUEST_TIMEOUT_MILLIS = 500;
        public static int MAX_CONN_PER_ROUTE = 10;
        public static int MAX_CONN_TOTAL = 30;
    
        private static HttpHost HTTP_HOST;
        private RestClientBuilder builder;
        private RestClient restClient;
        private RestHighLevelClient restHighLevelClient;
    
        private static ESClientSpringFactory esClientSpringFactory = new ESClientSpringFactory();
    
        private ESClientSpringFactory() {
        }
    
        public static ESClientSpringFactory build(HttpHost httpHost,
                                                  Integer maxConnectNum, Integer maxConnectPerRoute) {
            HTTP_HOST = httpHost;
            MAX_CONN_TOTAL = maxConnectNum;
            MAX_CONN_PER_ROUTE = maxConnectPerRoute;
            return esClientSpringFactory;
        }
    
        public static ESClientSpringFactory build(HttpHost httpHost, Integer connectTimeOut, Integer socketTimeOut,
                                                  Integer connectionRequestTime, Integer maxConnectNum, Integer maxConnectPerRoute) {
            HTTP_HOST = httpHost;
            CONNECT_TIMEOUT_MILLIS = connectTimeOut;
            SOCKET_TIMEOUT_MILLIS = socketTimeOut;
            CONNECTION_REQUEST_TIMEOUT_MILLIS = connectionRequestTime;
            MAX_CONN_TOTAL = maxConnectNum;
            MAX_CONN_PER_ROUTE = maxConnectPerRoute;
            return esClientSpringFactory;
        }
    
    
        public void init() {
            builder = RestClient.builder(HTTP_HOST);
            setConnectTimeOutConfig();
            setMutiConnectConfig();
            restClient = builder.build();
            restHighLevelClient = new RestHighLevelClient(builder);
            System.out.println("init factory");
        }
    
        // 配置连接时间延时
        public void setConnectTimeOutConfig() {
            builder.setRequestConfigCallback(requestConfigBuilder -> {
                requestConfigBuilder.setConnectTimeout(CONNECT_TIMEOUT_MILLIS);
                requestConfigBuilder.setSocketTimeout(SOCKET_TIMEOUT_MILLIS);
                requestConfigBuilder.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT_MILLIS);
                return requestConfigBuilder;
            });
        }
    
        // 使用异步httpclient时设置并发连接数
        public void setMutiConnectConfig() {
            builder.setHttpClientConfigCallback(httpClientBuilder -> {
                httpClientBuilder.setMaxConnTotal(MAX_CONN_TOTAL);
                httpClientBuilder.setMaxConnPerRoute(MAX_CONN_PER_ROUTE);
                return httpClientBuilder;
            });
        }
    
        public RestClient getClient() {
            return restClient;
        }
    
        public RestHighLevelClient getRhlClient() {
            return restHighLevelClient;
        }
    
        public void close() {
            if (restClient != null) {
                try {
                    restClient.close();
                } catch (IOException e) {
                    log.error("IO:", e);
                }
            }
            System.out.println("close client");
        }
    }

    Book

    package com.estestcase;
    
    import lombok.Data;
    
    @Data
    public class Book {
        private int id;
        private String bookName;
        private String author;
    }

    ResponseBean

    package com.estestcase;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    
    @Data
    @AllArgsConstructor
    public class ResponseBean {
        //状态码
        private Integer code;
        //返回信息
        private String message;
        //返回的数据
        private Object data;
    }

    BookController

    package com.estestcase;
    
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;
    import lombok.extern.slf4j.Slf4j;
    import org.elasticsearch.action.search.SearchRequest;
    import org.elasticsearch.action.search.SearchResponse;
    import org.elasticsearch.client.Client;
    import org.elasticsearch.client.RequestOptions;
    import org.elasticsearch.client.RestHighLevelClient;
    import org.elasticsearch.index.query.BoolQueryBuilder;
    import org.elasticsearch.search.SearchHit;
    import org.elasticsearch.search.SearchHits;
    import org.elasticsearch.search.builder.SearchSourceBuilder;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.io.IOException;
    
    @Slf4j
    @RestController
    public class BookController {
        @Autowired
        private RestHighLevelClient rhlClient;
    
        //@Autowired
        Client client;
    
        private BoolQueryBuilder boolQueryBuilder = null;
    
        @RequestMapping("search")
        public ResponseBean searchInfoByCursor1() {
            SearchRequest searchRequest = new SearchRequest("books");
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            log.info("***********************hello***********************");
            //如果用name直接查询,其实是匹配name分词过后的索引查到的记录(倒排索引);如果用
            sourceBuilder.query();
            try {
                SearchResponse response = rhlClient.search(searchRequest, RequestOptions.DEFAULT);
                SearchHits hits = response.getHits();
                JSONArray jsonArray = new JSONArray();
                for (SearchHit hit : hits) {
                    String sourceAsString = hit.getSourceAsString();
                    JSONObject jsonObject = JSON.parseObject(sourceAsString);
                    jsonArray.add(jsonObject);
                    log.info("输出:{}", jsonObject.toString());
                }
                return new ResponseBean(200, "查询成功", jsonArray);
            } catch (IOException e) {
                return new ResponseBean(10001, "查询失败", null);
            }
        }
    }

    EsTestcaseApplication

    package com.estestcase;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class EsTestcaseApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(EsTestcaseApplication.class, args);
        }
    
    }

    启动项目运行

     请求接口

    直接在浏览器请求:http://localhost:8080/search

     后台打印

     大功告成!!!

  • 相关阅读:
    Android开发学习笔记-SharedPreferences的用法
    Android开发学习笔记-自定义组合控件
    webpack 4 教程
    react 生命周期图解
    git 操作说明
    echars 3.0 去掉柱状图阴影用什么属性
    react——Table组件
    antd ——按钮
    react——Table组件列中靠左 靠右对齐解决方案
    react中异步的使用
  • 原文地址:https://www.cnblogs.com/weigy/p/14553887.html
Copyright © 2011-2022 走看看