RestHighLevelClient怎么连接有密码的Es
时间: 2023-11-08 11:04:37 浏览: 65
ElasticSearch RestHighLevelClient 关于索引库、文档的基础操作
要连接有密码的 Elasticsearch,你可以使用 `RestHighLevelClient` 的 `Builder` 类来设置连接参数。首先,你需要创建一个 `CredentialsProvider` 对象,用于提供连接凭证。然后,将该凭证提供者设置到 `Builder` 中,最后通过 `build()` 方法创建 `RestHighLevelClient` 的实例。
以下是一个示例代码:
```java
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
public class Main {
public static void main(String[] args) {
String hostname = "localhost"; // Elasticsearch 服务器主机名
int port = 9200; // Elasticsearch 服务器端口号
String username = "your-username"; // Elasticsearch 用户名
String password = "your-password"; // Elasticsearch 密码
// 创建凭证提供者并设置用户名和密码
final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
// 创建 RestClient 构建器
RestClientBuilder builder = RestClient.builder(new HttpHost(hostname, port, "http"))
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
// 创建 RestHighLevelClient 实例
RestHighLevelClient client = new RestHighLevelClient(builder);
// 使用 client 进行操作...
// 关闭客户端连接
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
阅读全文