elasticsearch 从Java客户端连接到弹性云

atmip9wb  于 2022-11-28  发布在  ElasticSearch
关注(0)|答案(1)|浏览(196)

我一直在尝试使用Java客户端连接到弹性云上的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客户端连接到Elastic Cloud上的ES的最佳方式是什么?

pzfprimi

pzfprimi1#

1.登录后转到cloud.elastic.go/home,找到“管理此部署”链接。它应该类似于https://cloud.elastic.co/deployments/xxxxxxxx
1.在“应用程序”下,您应该有一个“ElasticSearch”端点(单击“复制端点”)
1.在API控制台上创建API密钥:

POST /_security/api_key 
{
  "name": "my_key_name",
  "expiration": "15d"
}

这会给予你一些类似的东西:

{
  "id": "API_KEY_ID",
  "name": "my_key_name",
  "expiration": 1670471984009,
  "api_key": "API_KEY",
  "encoded": "XxxxxxxxXXXXXxxxxxxXXXXxxxxxXXXX=="
}

1.现在在Java代码中:

// endpoint you copied
String hostname = "youdepname.es.us-west1.gcp.cloud.es.io";
String apiKeyId = "API_KEY_ID";
String apiKeySecret = "API_KEY";
String apiKeyAuth =
     Base64.getEncoder().encodeToString(
         (apiKeyId + ":" + apiKeySecret)
             .getBytes(StandardCharsets.UTF_8));

RestClientBuilder builder = RestClient.builder(
     new HttpHost(hostname, 9243, "https"))
     .setRequestConfigCallback(
         new RestClientBuilder.RequestConfigCallback() {
           @Override
           public RequestConfig.Builder customizeRequestConfig(
               RequestConfig.Builder requestConfigBuilder) {
             return requestConfigBuilder
                 .setConnectTimeout(5000)
                 .setSocketTimeout(60000);
           }
         });

Header[] defaultHeaders =
     new Header[]{new BasicHeader("Authorization",
         "ApiKey " + apiKeyAuth)};
builder.setDefaultHeaders(defaultHeaders);

RestClient restClient = builder.build();

// Create the transport with a Jackson mapper
ElasticsearchTransport transport = new RestClientTransport(
     restClient, new JacksonJsonpMapper());

// And create the API client
ElasticsearchClient client = new ElasticsearchClient(transport);

应该可以了。还有其他的连接方式,但这是我的首选方式。

相关问题