先貼代碼
@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 依舊可以正常操作,但是后端依舊報一樣的錯