• springboot集成Elasticsearch7.16,使用https方式连接并忽略SSL证书


    千万万苦利用科学上网找到了,记录一下

    package com.warn.config.baseconfig;
    
    import co.elastic.clients.elasticsearch.ElasticsearchClient;
    import co.elastic.clients.json.jackson.JacksonJsonpMapper;
    import co.elastic.clients.transport.ElasticsearchTransport;
    import co.elastic.clients.transport.rest_client.RestClientTransport;
    import com.alibaba.fastjson.JSONObject;
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    import com.common.util.text.Convert;
    import com.warn.entity.SettingVar;
    import com.warn.mapper.SettingVarMapper;
    import com.warn.util.EncryptUtil;
    import lombok.extern.slf4j.Slf4j;
    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.client.config.RequestConfig;
    import org.apache.http.conn.ssl.NoopHostnameVerifier;
    import org.apache.http.impl.client.BasicCredentialsProvider;
    import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
    import org.apache.http.ssl.SSLContextBuilder;
    import org.apache.http.ssl.SSLContexts;
    import org.elasticsearch.client.RestClient;
    import org.elasticsearch.client.RestClientBuilder;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import javax.annotation.Resource;
    import javax.net.ssl.SSLContext;
    import java.io.File;
    
    /**
     * @author fjl
     * @date 2022/5/6
     */
    @Slf4j
    @Configuration
    public class ElasticSearchClientConfig {
    
        @Resource
        private SettingVarMapper varMapper;
    
        @Value("${es.connectTimeout}")
        private Integer connectTimeout;
    
        @Value("${es.socketTimeout}")
        private Integer socketTimeout;
        private static final Integer ES_ID = 30;
    
        @Value("${filePath}")
        private String filePath;
        private static String esInfo = "esInfo.txt";
    
        public static String esUrl;
    
        public static Integer esPort;
    
        public static String esAccount;
    
        public static String esPassword;
    
    
        //配置RestHighLevelClient依赖到spring容器中待用
        @Bean
        public ElasticsearchClient restHighLevelClient() throws Exception {
            log.info("--- 初始化es链接开始 --- ");
            EncryptUtil.checkFileExist(filePath);
            String esFilePath = filePath + esInfo;
            File esFile = new File(esFilePath);
            boolean esExists = esFile.exists();
            log.info("---  检查es地址文件是否存在 --- {} esPath:{} ", esExists, esFilePath);
            if (!esExists) {
                // 获取es地址
                LambdaQueryWrapper<SettingVar> wrapper = new LambdaQueryWrapper<SettingVar>()
                        .eq(SettingVar::getId, ES_ID)
                        .select(SettingVar::getValue);
                SettingVar settingVar = varMapper.selectOne(wrapper);
                if (null != settingVar) {
                    log.info("--- es地址信息  {}", settingVar.getValue());
                    String value = settingVar.getValue();
                    getEsAddr(value);
                    // 创建文件并写入
                    EncryptUtil.createFile(esFilePath, value);
                }
            } else {
                // 存在读取赋值
                String value = EncryptUtil.readLine(esFilePath);
                getEsAddr(value);
                log.info("***  es地址读取完成 --- {} ", value);
            }
    
            try {
                CredentialsProvider credentialsProvider =
                        new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY,
                        new UsernamePasswordCredentials(esAccount, esPassword));
    
                SSLContextBuilder sslBuilder = SSLContexts.custom()
                        .loadTrustMaterial(null, (x509Certificates, s) -> true);
                final SSLContext sslContext = sslBuilder.build();
                RestClientBuilder restBuilder = RestClient.builder(
                                new HttpHost(esUrl, esPort, "https"))
                        .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                            @Override
                            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                                return httpClientBuilder
                                        .setSSLContext(sslContext)
                                        .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                                        .setDefaultCredentialsProvider(credentialsProvider);
                            }
                        })
                        .setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
                            @Override
                            public RequestConfig.Builder customizeRequestConfig(
                                    RequestConfig.Builder requestConfigBuilder) {
                                return requestConfigBuilder.setConnectTimeout(5000)
                                        .setSocketTimeout(120000);
                            }
                        });
                RestClient restClient = restBuilder.build();
                ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
                ElasticsearchClient client = new ElasticsearchClient(transport);
                log.info("*** 初始化es链接完成 *** ");
    
                return client;
            } catch (Exception e) {
                throw new Exception("******  es初始化连接失败");
            }
        }
    
        public void getEsAddr(String value) {
            JSONObject jsonObject = JSONObject.parseObject(value);
            String url = com.common.util.text.Convert.toStr(jsonObject.get("addr"));
            int port = com.common.util.text.Convert.toInt(jsonObject.get("port"));
            String account = com.common.util.text.Convert.toStr(jsonObject.get("account"));
            String password = Convert.toStr(jsonObject.get("password"));
            esUrl = url;
            esPort = port;
            esAccount = account;
            esPassword = password;
        }
    }
    
    • 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
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
  • 相关阅读:
    Python3.8+PyCharm安装和简单配置
    MySQL -- mysql connect
    Mangopi MQ-R:T113-s3编译Tina Linux系统(二)SDK目录
    数据治理系列:数仓建模之数仓主题与主题域
    求和中x:y=g(x)的含义
    物理层课后作业
    EN 1154建筑五金件受控关门装置—CE认证
    笔记本电脑没有声音?几招恢复声音流畅!
    SpringCloud 学习(一)---- 微服务的概念
    MySQL忘记密码后重置密码(windows版本)
  • 原文地址:https://blog.csdn.net/qq_40310480/article/details/132710857