java连接ES集群,ES带有账号密码
时间: 2023-07-08 13:46:09 浏览: 131
连接带有账号密码的ES集群,可以使用Java High Level Rest Client。下面是一个简单的Java代码示例,展示如何连接带有账号密码的ES集群:
```java
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.sniff.Sniffer;
import org.elasticsearch.common.settings.Settings;
import java.util.Arrays;
public class ESClient {
private static final String[] esHosts = {"localhost:9200"};
private static final String userName = "yourUserName";
private static final String password = "yourPassword";
private static final String schema = "https";
private static RestHighLevelClient client;
static {
HttpHost[] hosts = Arrays.stream(esHosts).map(HttpHost::create).toArray(HttpHost[]::new);
client = new RestHighLevelClient(RestClient.builder(hosts)
.setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder
.setDefaultCredentialsProvider(() -> new UsernamePasswordCredentials(userName, password)))
.setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder
.setConnectTimeout(5000)
.setSocketTimeout(60000)));
}
public static RestHighLevelClient getClient() {
return client;
}
public static void closeClient() {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的示例代码中,我们使用RestClient.builder()创建了RestHighLevelClient实例,并通过setHttpClientConfigCallback()设置了HTTP客户端的配置。其中,setDefaultCredentialsProvider()方法设置了用户名和密码,用于连接ES集群。如果ES集群启用了HTTPS,则需要设置schema为https。
需要注意的是,这里的示例代码并没有启用连接池,如果需要使用连接池,可以参考Elasticsearch官方文档中提供的Rest Client连接池实现。
阅读全文