You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 04:48:01