1. 程式人生 > 其它 >記一次使用RestHighLevelClient連線ElasticSearch 7.12.0 https 域名遇到的坑

記一次使用RestHighLevelClient連線ElasticSearch 7.12.0 https 域名遇到的坑

先貼程式碼

    @Bean
    @Override
    public RestHighLevelClient elasticsearchClient() {
        //連線 HTTPS 協議 使用 賬號密碼驗證
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(Constant.ES_USERNAME, Constant.ES_PASSWORD));
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        //使用 new 方式生成 HttpHost 只能生成 HTTP 協議的連線,即使 傳入 'https://xxx' 生成的結果也會變成 'http://https://xxx'
                        //new HttpHost(Constant.ES_HOST);
                        HttpHost.create(Constant.ES_HOST)
                ).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        httpClientBuilder.disableAuthCaching();
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                })
        );

        //   原生連線本地
        /*RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")));
        return client;*/
    }

由於運維方提供的伺服器域名地址為 https 協議,沒有留意,導致程式碼測試時,遇到如下情況

  • postman 測試直連 es 進行 CRUD 返回結果一切正常
  • 後端執行程式碼後,查詢正常,但是增刪改報出異常 308 ,以及無法解析返回響應體 ElasticsearchStatusException[Unable to parse response body]
  • postman 中把 https 改為 http 依舊可以正常操作,但是後端依舊報一樣的錯