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

Java Client连接Elastic Cloud报错连接拒绝,求正确连接方案

问题描述

我按照Elastic官方文档尝试用Java Client连接Elastic Cloud上的ES实例,但一直失败。使用的主机名是https://myinstance-xx.europe-west1.gcp.cloud.es.io,配置代码如下:

private String hostName = "https://myinstance-xx.es.europe-west1.gcp.cloud.es.io";
private String username = "username";
private String password = "pass";
@Bean
public ElasticsearchClient client() {
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(username, password));
    RestClientBuilder builder = RestClient.builder(new HttpHost(hostName, 9200))
            .setHttpClientConfigCallback(httpClientBuilder ->
                    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
    // Create the low-level client
    RestClient restClient = builder.build();
    // Create the transport with a Jackson mapper
    ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
    // And create the API client
    return new ElasticsearchClient(transport);
}

运行时抛出异常:

java.net.ConnectException: Connection refused

请问通过Java Client连接Elastic Cloud上ES实例的正确方式是什么?

解决方法

你的代码存在两个核心问题:

  • HttpHost构造错误:传入的hostName包含https://前缀,HttpHost会将整个字符串当作主机名解析,导致无法正确识别目标地址;同时Elastic Cloud的ES实例默认使用443端口而非9200。
  • 缺少SSL配置:Elastic Cloud实例强制使用HTTPS协议,必须配置SSL上下文以信任云端证书。

正确的配置代码如下:

private String hostName = "myinstance-xx.europe-west1.gcp.cloud.es.io"; // 移除https://前缀
private String username = "username";
private String password = "pass";

@Bean
public ElasticsearchClient client() {
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(username, password));

    RestClientBuilder builder = RestClient.builder(new HttpHost(hostName, 443, "https"))
            .setHttpClientConfigCallback(httpClientBuilder ->
                    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
                            // 配置SSL上下文,此处为默认信任(生产环境建议导入指定CA证书)
                            .setSSLContext(SSLContext.getDefault()));

    RestClient restClient = builder.build();
    ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
    return new ElasticsearchClient(transport);
}

额外注意事项:

  • 生产环境中,请勿使用SSLContext.getDefault(),应将Elastic Cloud控制台提供的CA证书导入到项目的信任库中,再构建安全的SSL上下文,避免潜在的安全风险。
  • 确认主机名、用户名、密码与Elastic Cloud控制台中实例的配置完全一致,主机名务必不要包含协议前缀。

内容的提问来源于stack exchange,提问作者Ala A.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:55:22