當(dāng)你需要通過(guò)RestClient連接Elasticsearch,此時(shí)提供的Elasticsearch服務(wù)處于安全考慮塑悼,需要通過(guò)提供的證書(shū)進(jìn)行加密訪(fǎng)問(wèn)馋嗜,也可以通過(guò) HttpClientConfigCallback
配置使用 TLS 的加密通信辐啄。 作為參數(shù)接收的 org.apache.http.impl.nio.client.HttpAsyncClientBuilder
公開(kāi)了多種配置加密通信的方法:setSSLContext
澈魄、setSSLSessionStrategy
和 setConnectionManager
景鼠,按優(yōu)先級(jí)從最不重要的順序排列。
訪(fǎng)問(wèn)在 HTTP 層上為 TLS 設(shè)置的 Elasticsearch 集群時(shí)痹扇,客戶(hù)端需要信任 Elasticsearch 正在使用的證書(shū)铛漓。 以下是設(shè)置客戶(hù)端以信任已簽署 Elasticsearch 正在使用的證書(shū)的 CA 的示例,當(dāng)該 CA 證書(shū)在 PKCS#12 密鑰庫(kù)中可用時(shí):
Path trustStorePath = Paths.get("/path/to/truststore.p12");
KeyStore truststore = KeyStore.getInstance("pkcs12");
try (InputStream is = Files.newInputStream(trustStorePath)) {
truststore.load(is, keyStorePass.toCharArray());
}
SSLContextBuilder sslBuilder = SSLContexts.custom()
.loadTrustMaterial(truststore, null);
final SSLContext sslContext = sslBuilder.build();
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200, "https"))
.setHttpClientConfigCallback(new HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder.setSSLContext(sslContext);
}
});
下面是我們需要提供Keystore和TrustStore的場(chǎng)景:
public static RestHighLevelClient initRestHighLevelClient() {
try {
KeyStore keyStore =KeyStore.getInstance("jceks"); //Depands on your keyStoreType
keyStore.load(new FileInputStream(keyStorePath), keyStorePwd.toCharArray());
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadKeyMaterial(keyStore, keyStorePwd.toCharArray());
builder.loadTrustMaterial(new File(trustStorePath));
final SSLContext context = builder.build();
List<HttpHost> hostLists = new ArrayList<>();
String[] hostList = address.split(",");
for (String addr : hostList) {
String host = addr.split(":")[0];
String port = addr.split(":")[1];
hostLists.add(new HttpHost(host, Integer.parseInt(port), "https"));
}
HttpHost[] httpHost = hostLists.toArray(new HttpHost[]{});
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
RestClientBuilder restClientBuilder = RestClient
.builder(httpHost)
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider).setSSLContext(context);
}
});
return new RestHighLevelClient(restClientBuilder);
} catch (Exception e) {
log.error("=======init RestHighLevelClient faild : " + e.getMessage());
return null;
}
}
更多其他加密通信場(chǎng)景可參考官網(wǎng):
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/_encrypted_communication.html