Spring Data Elasticsearch配置带context-path的反向代理ES地址报错如何处理
问题根因
Spring Boot 2.4.6版本自带的Elasticsearch Rest客户端自动配置逻辑,不支持直接在spring.elasticsearch.rest.uris配置项中填写带路径前缀的地址,解析时会把包含路径的完整串误判为主机名进行DNS解析,最终抛出java.net.UnknownHostException异常。
解决方案
方案一:自定义RestHighLevelClient配置(无需升级版本,适配性最强)
首先拆分原有配置,在application.properties中保留鉴权配置,去掉uri中的路径前缀:
spring.elasticsearch.rest.username=elastic spring.elasticsearch.rest.password=blabla
新增Elasticsearch自定义配置类,手动指定代理路径前缀:
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.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration; @Configuration public class ElasticsearchConfig extends AbstractElasticsearchConfiguration { @Value("${spring.elasticsearch.rest.username}") private String esUsername; @Value("${spring.elasticsearch.rest.password}") private String esPassword; @Override @Bean public RestHighLevelClient elasticsearchClient() { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(esUsername, esPassword)); return new RestHighLevelClient( RestClient.builder(new HttpHost("admin-integration.hello.com", 443, "https")) // 配置反向代理要求的统一路径前缀 .setPathPrefix("/elasticsearch/api") .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)) ); } }
方案二:升级Spring Boot版本使用原生配置支持
如果你的项目允许升级Spring Boot版本,升级到2.5.0及以上版本后,官方新增了spring.elasticsearch.rest.path-prefix配置项,直接拆分配置即可:
spring.elasticsearch.rest.uris=https://admin-integration.hello.com spring.elasticsearch.rest.path-prefix=/elasticsearch/api spring.elasticsearch.rest.username=elastic spring.elasticsearch.rest.password=blabla
内容的提问来源于stack exchange,提问作者christophe spielmann
相关产品推荐
相关产品推荐

