我试图使用RestHighLevelClient连接到我的Elasticsearch集群,但它似乎对我不起作用。以下是我使用的代码段。
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
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.apache.http.message.BasicHeader;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
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 java.util.Base64;
@Configuration
public class ElasticSearchConfig {
@Value("${elasticsearch.host}")
private String host;
@Value("${elasticsearch.port}")
private int port;
@Value("${elasticsearch.username}")
private String username;
@Value("${elasticsearch.password}")
private String password;
@Bean(destroyMethod = "close")
public RestHighLevelClient esClient() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
System.out.println("header " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes()));
String encodedBytes = Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
RestClientBuilder builder = RestClient.builder(new HttpHost(host, 9243,"https"));
/*Header[] headers = {new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"),
new BasicHeader("Authorization", "Basic " + encodedBytes)};
*/
builder.setHttpClientConfigCallback(
httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
//builder.setDefaultHeaders(headers);
System.out.println("password" + credentialsProvider.getCredentials(AuthScope.ANY).getPassword());
System.out.println("name" + credentialsProvider.getCredentials(AuthScope.ANY).getUserPrincipal().getName());
return new RestHighLevelClient(builder);
}
}
我尝试通过cURL使用相同的主机名,端口和凭据集(“username:password”的Base 64编码字符串)进行连接,但是以编程方式给了我UnknownHostException,这很奇怪,很感谢您的帮助。
编辑
我正在使用正在使用cURL的9243,并且我尝试了9200、9300,以防万一,但无济于事。
最佳答案
一个小的但重要的更正。使用Elastic Search的默认设置时,您应该连接到端口9200 。
请阅读官方文档:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-getting-started-initialization.html