java ssl elastic_es集群开启ssl后,java如何连接es集群
时间: 2024-03-09 13:50:24 浏览: 68
要连接开启了SSL的Elasticsearch集群,需要使用Java的TransportClient,并使用SSLContext来设置SSL连接。以下是一个简单的示例代码:
```java
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import javax.net.ssl.SSLContext;
import java.net.InetAddress;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class ESClient {
public static void main(String[] args) throws Exception {
Settings settings = Settings.builder()
.put("cluster.name", "myClusterName")
.put("xpack.security.user", "myUsername:myPassword")
.put("xpack.security.transport.ssl.enabled", true)
.put("xpack.security.transport.ssl.verification_mode", "certificate")
.put("xpack.security.transport.ssl.keystore.path", "/path/to/keystore.jks")
.put("xpack.security.transport.ssl.truststore.path", "/path/to/truststore.jks")
.build();
SSLContext sslContext = SSLContext.getInstance("TLS");
KeyStore keyStore = KeyStore.getInstance("jks");
KeyStore trustStore = KeyStore.getInstance("jks");
keyStore.load(ESClient.class.getResourceAsStream("/path/to/keystore.jks"), "keystore_password".toCharArray());
trustStore.load(ESClient.class.getResourceAsStream("/path/to/truststore.jks"), "truststore_password".toCharArray());
TrustManager[] trustManagers = new TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
}};
sslContext.init(null, trustManagers, new SecureRandom());
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300))
.setSSLContext(sslContext);
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject().field("name", "John").endObject();
client.prepareIndex("myindex", "mytype", "1")
.setSource(builder)
.get();
client.close();
}
}
```
在这个示例代码中,我们首先使用Elasticsearch的TransportClient创建了一个连接,然后设置了连接ES集群所需的一些参数。其中,`xpack.security.user`参数是用于认证的用户名和密码,`xpack.security.transport.ssl.enabled`参数设置为`true`表示开启SSL连接,`xpack.security.transport.ssl.verification_mode`参数设置为`certificate`表示只信任CA签署的证书。最后,我们设置了keystore和truststore的路径,并使用SSLContext将其加载。
接下来,我们使用TransportClient发送了一个简单的索引请求,将一个JSON文档插入到名为`myindex`、类型为`mytype`、ID为`1`的索引中。
注意,这只是一个简单的示例,实际应用中还需要根据实际情况进行配置和调整。
阅读全文