elasticsearch设置密码及Java密码连接
目录
1. 安装
2. 修改elasticsearch-8.2.2\config\elasticsearch.yml文件里面xpack.security.enabled: false为
xpack.security.enabled: true
3. 重新启动es
4. 重置密码
elasticsearch-8.2.2\bin\elasticsearch-reset-password.bat -u elastic -i
按提示输入y
然后再输入2次密码
123456
参考文章:https://blog.csdn.net/weixin_38285720/article/details/123589570
5. 访问
- 直接访问:https://localhost:9200然后输入账号密码
- head访问:https://localhost:9100里面输入https://localhost:9200/?auth_user=elastic&auth_password=123456
6. Java连接
Java连接简单使用ElasticSearch
获取客户端方法修改为下面
public static RestClient getClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException, CertificateException, IOException {
// 如果有多个从节点可以持续在内部new多个HttpHost,参数1是ip,参数2是HTTP端口,参数3是通信协议
// RestClientBuilder clientBuilder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
RestClientBuilder clientBuilder = RestClient.builder(new HttpHost("localhost", 9200, "https"));
final CredentialsProvider credentialsProvider =
new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("elastic", "123456"));
// TODO 注意安装路径
Path caCertificatePath = Paths.get("F:\\安装包\\elasticsearch-8.2.2\\config\\certs\\http_ca.crt");
CertificateFactory factory =
CertificateFactory.getInstance("X.509");
Certificate trustedCa;
try (InputStream is = Files.newInputStream(caCertificatePath)) {
trustedCa = factory.generateCertificate(is);
}
KeyStore trustStore = KeyStore.getInstance("pkcs12");
trustStore.load(null, null);
trustStore.setCertificateEntry("ca", trustedCa);
SSLContextBuilder sslContextBuilder = SSLContexts.custom()
.loadTrustMaterial(trustStore, null);
final SSLContext sslContext = sslContextBuilder.build();
clientBuilder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider));
return clientBuilder.build();
}
7. 附elasticsearch.yml文件
xpack.security.enabled: true
xpack.security.enrollment.enabled: true
xpack.security.http.ssl:
enabled: true
keystore.path: certs/http.p12
xpack.security.transport.ssl:
enabled: true
verification_mode: certificate
keystore.path: certs/transport.p12
truststore.path: certs/transport.p12
cluster.initial_master_nodes: ["DESKTOP-S42LMR1"]
cluster.name: germey-es-clusters
node.name: es-node-1
http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.allow-headers: Authorization,X-Requested-With,Content-Length,Content-Type
8. 参考文章
参考文章:https://elasticstack.blog.csdn.net/article/details/124247310