• Springboot整合ElasticSearch(1)- 环境搭建 -非自动注入的方式


    Springboot 整合ElasticSearch(1)

    1、基本信息

    1、SpringBoot 版本 : 2.7.14
       
            org.springframework.boot
            spring-boot-starter-parent
            2.7.14
             
        
        
    2、ElasticSearch版本 : 7.9.1
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    2、添加依赖

        <properties>
            
            <java.version>1.8java.version>
            
            <elasticsearch.version>7.9.1elasticsearch.version>
        properties>
    
    
    
        <dependencies>
    	    
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starterartifactId>
            dependency>
            <dependency>
    		    <groupId>org.springframework.bootgroupId>
    		    <artifactId>spring-boot-configuration-processorartifactId>
    		    <optional>trueoptional>
    		dependency>
    
            
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-data-elasticsearchartifactId>
            dependency>
            
        dependencies>
    
    
    • 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

    3.配置elasticsearch的属性

    在application.yaml中添加如下数据

    es:
      clusterName: clusterTestEs # es集群的名称
      userName: userName # es集群的访问用户名
      passWord: password # es集群的访问密码
      nodes: # es集群的节点列表
        - 192.168.2.5:9200
        - 192.168.2.6:9200
        - 192.168.2.7:9200
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    4.构造elasticsearch的属性配置类

    通过配置类的方式读取application.yaml中的属性

    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.Configuration;
    
    import java.util.List;
    
    @Configuration
    @ConfigurationProperties(prefix = "es") // 指定配置的前缀
    public class ElasticSearchProperties {
    
        private String clusterName;
        private String userName;
        private String passWord;
        private List<String> nodes;
    
    	// 下面是正常的 无参构造、有参构造、getter方法、setter方法、toString() 方法
         。。。。。。
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    5.构造elasticsearch 客户端对象配置类

    主要是创建一个RestHighLevelClient 类型的客户端对象,在实际操作过程中都要用到这个对象。
    下面的这个方法,直接照抄即可,无需进行修改。

    import org.apache.commons.lang3.StringUtils;
    import org.apache.http.HttpHost;
    import org.apache.http.auth.AuthScope;
    import org.apache.http.auth.UsernamePasswordCredentials;
    import org.apache.http.client.CredentialsProvider;
    import org.apache.http.impl.client.BasicCredentialsProvider;
    import org.elasticsearch.client.Node;
    import org.elasticsearch.client.RestClient;
    import org.elasticsearch.client.RestClientBuilder;
    import org.elasticsearch.client.RestHighLevelClient;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import java.util.List;
    import java.util.Objects;
    
    
    @Configuration
    public class ElasticSearchConfig  {
    
        private Logger logger = LoggerFactory.getLogger(ElasticSearchConfig.class);
    
        private static final int ADDRESS_LENGTH = 2;
        private static final String HTTP_SCHEME = "http";
    
        @Autowired
        private ElasticSearchProperties esProperties;
    
        @Bean
        public RestClientBuilder restClientBuilder() {
    
            List<String> nodes = esProperties.getNodes();
            HttpHost[] httpHosts = nodes.stream()
                    .map(this::makeHttpHost)
                    .filter(Objects::nonNull)
                    .toArray(HttpHost[]::new);
            return RestClient.builder(httpHosts);
        }
    
    	/**
    	* 下面的这个bean 是一个创建客户端的核心的 bean
    	*/
        @Bean(name = "highLevelClient")
        public RestHighLevelClient highLevelClient(@Autowired RestClientBuilder restClientBuilder){
            //配置身份验证 : 就是用户名密码
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                       new UsernamePasswordCredentials(esProperties.getUserName(), esProperties.getPassWord()));
            restClientBuilder.setHttpClientConfigCallback(
                    httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider).disableAuthCaching());
            //设置连接超时和套接字超时
            restClientBuilder.setRequestConfigCallback(
                    requestConfigBuilder -> requestConfigBuilder.setSocketTimeout(10000).setConnectTimeout(60000));
            
            //设置监听器,每次节点失败都可以监听到,可以作额外处理
            restClientBuilder.setFailureListener(new RestClient.FailureListener() {
                @Override
                public void onFailure(Node node) {
                    super.onFailure(node);
                    logger.error(node.getHost() + "--->该节点失败了");
                }
            });
            // 返回客户端对象
            return new RestHighLevelClient(restClientBuilder);
        }
    
    	// 处理节点的方法,把配置文件的节点的IP和端口号拆分开,创建HttpHost对象
        private HttpHost makeHttpHost(String str) {
            assert StringUtils.isNotEmpty(str);
            String[] address = str.split(":");
            if (address.length == ADDRESS_LENGTH) {
                String ip = address[0];
                int port = Integer.parseInt(address[1]);
                logger.info("ES连接ip和port:{},{}", ip, port);
                return new HttpHost(ip, port, HTTP_SCHEME);
            } else {
                logger.error("传入的ip参数不正确!");
                return null;
            }
        }
    }
    
    
    • 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
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85

    6.创建一个工具类,封装一些工具方法

    经过以上5个步骤,已经成功配置并且获取到了操作elasticsearch的客户端对象,
    下面就可以使用该客户端对象进行操作了。
    因此,可以使用该对象进行一些常用方法的封装,下面的代码以判断索引库是否存在为例,进行演示。

    
    import org.elasticsearch.client.RestHighLevelClient;
    
    import org.elasticsearch.client.indices.GetIndexRequest;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.stereotype.Component;
    
    @Component
    public class ElasticSearchUtil {
    
        @Qualifier("highLevelClient")
        @Autowired
        private RestHighLevelClient rhlClient;
    
        private static  RestHighLevelClient client;
    
        /**
         * spring容器初始化的时候执行该方法
         */
        @PostConstruct
        public void init() {
            client = this.rhlClient;
            log.info("esclient 对象初始化success!{}",client);
        }
    
    
        /**
         * 判断索引是否存在
         * @param indexName
         * @throws Exception
         */
        public void judgeIndexExist(String indexName) throws Exception{
            GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);
            boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
    
            System.out.println(indexName + "  exists ?  : " + exists);
    
        }
    
    }
    
    
    • 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
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    7.测试是否可以正常使用

    测试思路 :
    1.在spring boot中编写一个简单的接口,接口中节点调用一下 步骤6中的方法。
    2.访问接口看是否能够正常获取到状态即可。

    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    
    @RestController
    @RequestMapping("/test")
    public class EsController  {
    
        @Autowired
        private ElasticSearchUtil elasticSearchUtil;
    
    
        @PostMapping("/judgeIndexState")
        public String createIndex(@RequestBody String indexName){
    
            logger.info("参数索引名称是 : "+indexName);
            try {
            	// 直接调用工具方法中的参数即可
                elasticSearchUtil.judgeIndexExist(indexName);
                
            }catch (Exception e){
                e.printStackTrace();
            }
    
            return "-"+indexName;
        }
    }
    
    • 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

    8.完成

    在步骤7中访问成功后,即表示当前的集成工作完成。

  • 相关阅读:
    Vue详解及综合案例
    《对比Excel,轻松学习Python数据分析》读书笔记------数值操作
    Python中对字典的几个处理
    计算机视觉系列 -MMDetection 之SSDLite经典算法
    thymeleaf抽取公共页面
    【Python零基础入门篇 · 17】:模块、模块的使用、过滤执行代码写法、包的使用
    qtcanpool 知 07:Ribbon
    【国外框架】—— quasar 响应式
    mac虚拟机搭建&设置静态ip
    QT:tcpSocket 报错The proxy type is invalid for this operation
  • 原文地址:https://blog.csdn.net/qq_39505245/article/details/133084369