Commit f34a7b4f authored by shiyu's avatar shiyu

es config

parent 04113729
......@@ -129,6 +129,6 @@
<artifactId>elasticsearch-java</artifactId>
<version>8.8.2</version>
</dependency>
</dependencies>
</dependencies>
</project>
package com.wwdz.ch.core.config;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.message.BasicHeader;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder.HttpClientConfigCallback;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
@Component
public class ElasticSearchConfig {
/**
* 多个ip用逗号隔开
*/
@Value("${spring.elasticsearch.jest.uris}")
private String elasticsearchUris;
@Value("${spring.elasticsearch.jest.username}")
private String username;
@Value("${spring.elasticsearch.jest.password}")
private String password;
private final static String crtName = "za-test.crt";
/**
* 解析配置的字符串,转为HttpHost对象数组
* @return
*/
private HttpHost[] toHttpHost() {
if (!StringUtils.hasLength(elasticsearchUris)) {
throw new RuntimeException("invalid elasticsearch configuration");
}
String[] hostArray = elasticsearchUris.split(",");
HttpHost[] httpHosts = new HttpHost[hostArray.length];
HttpHost httpHost;
for (int i = 0; i < hostArray.length; i++) {
String[] strings = hostArray[i].split(":");
httpHost = new HttpHost(strings[0], Integer.parseInt(strings[1]), "https");
httpHosts[i] = httpHost;
}
return httpHosts;
}
@Bean
public ElasticsearchClient clientByPasswd() throws Exception {
ElasticsearchTransport transport = getElasticsearchTransport(username, password, toHttpHost());
return new ElasticsearchClient(transport);
}
private static SSLContext buildSSLContext() {
ClassPathResource resource = new ClassPathResource(crtName);
SSLContext sslContext = null;
try {
CertificateFactory factory = CertificateFactory.getInstance("X.509");
Certificate trustedCa;
try (InputStream is = resource.getInputStream()) {
trustedCa = factory.generateCertificate(is);
}
KeyStore trustStore = KeyStore.getInstance("pkcs12");
trustStore.load(null, null);
trustStore.setCertificateEntry("ca", trustedCa);
SSLContextBuilder sslContextBuilder = SSLContexts.custom()
.loadTrustMaterial(trustStore, null);
sslContext = sslContextBuilder.build();
} catch (CertificateException | IOException | KeyStoreException | NoSuchAlgorithmException |
KeyManagementException e) {
e.printStackTrace();
}
return sslContext;
}
private static ElasticsearchTransport getElasticsearchTransport(String username, String passwd, HttpHost...hosts) {
// 账号密码的配置
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, passwd));
// 自签证书的设置,并且还包含了账号密码
HttpClientConfigCallback callback = httpAsyncClientBuilder -> httpAsyncClientBuilder
.setSSLContext(buildSSLContext())
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.setDefaultCredentialsProvider(credentialsProvider);
// 用builder创建RestClient对象
RestClient client = RestClient
.builder(hosts)
.setHttpClientConfigCallback(callback)
.build();
return new RestClientTransport(client, new JacksonJsonpMapper());
}
private static ElasticsearchTransport getElasticsearchTransport(String apiKey, HttpHost...hosts) {
// 将ApiKey放入header中
Header[] headers = new Header[] {new BasicHeader("Authorization", "ApiKey " + apiKey)};
// es自签证书的设置
HttpClientConfigCallback callback = httpAsyncClientBuilder -> httpAsyncClientBuilder
.setSSLContext(buildSSLContext())
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
// 用builder创建RestClient对象
RestClient client = RestClient
.builder(hosts)
.setHttpClientConfigCallback(callback)
.setDefaultHeaders(headers)
.build();
return new RestClientTransport(client, new JacksonJsonpMapper());
}
@Bean
public ElasticsearchClient clientByApiKey() throws Exception {
String apikey = null;
ElasticsearchTransport transport = getElasticsearchTransport(apikey, toHttpHost());
return new ElasticsearchClient(transport);
}
}
......@@ -2,6 +2,7 @@ package com.wwdz.ch.core.util;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch._types.query_dsl.TermQuery;
import co.elastic.clients.elasticsearch.core.GetResponse;
......@@ -17,6 +18,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
......@@ -28,7 +30,7 @@ public class ElasticsearchUtil {
private final static String INDEX = "quanku";
@Autowired
@Resource(name="clientByPasswd")
ElasticsearchClient elasticsearchClient;
public List<? extends Entity> findDocument(EsSearchParam esSearchParam) {
......@@ -48,19 +50,19 @@ public class ElasticsearchUtil {
.order(SortOrder.Desc)));
Query nameQuery = TermQuery.of(m -> m
Query nameQuery = MatchQuery.of(m -> m
.field("name")
.value(esSearchParam.getContent())
.query(esSearchParam.getContent())
)._toQuery();
SearchResponse<ItemOfEs> searchResponse = elasticsearchClient.search((Function<SearchRequest.Builder, ObjectBuilder<SearchRequest>>) builder, ItemOfEs.class);
// SearchResponse<ItemOfEs> searchResponse = elasticsearchClient.search((Function<SearchRequest.Builder, ObjectBuilder<SearchRequest>>) builder, ItemOfEs.class);
/* SearchResponse<ItemOfEs> searchResponse = elasticsearchClient.search(s -> s
SearchResponse<ItemOfEs> searchResponse = elasticsearchClient.search(s -> s
.index(INDEX)
.query(nameQuery)
// .query(nameQuery)
.from(page).size(size)
.sort(f -> f.field(o -> o.field("coin_id").order(SortOrder.Desc))),
ItemOfEs.class);*/
ItemOfEs.class);
logger.info("getResponse:{}", searchResponse);
List<Hit<ItemOfEs>> hitList = searchResponse.hits().hits();
for (Hit<ItemOfEs> itemOfEsHit : hitList) {
......
-----BEGIN CERTIFICATE-----
MIIDJDCCAgygAwIBAgIVAISkRi2NSeq3pdJMVfYkU4odK0vAMA0GCSqGSIb3DQEB
CwUAMDQxMjAwBgNVBAMTKUVsYXN0aWMgQ2VydGlmaWNhdGUgVG9vbCBBdXRvZ2Vu
ZXJhdGVkIENBMCAXDTIzMDYzMDAzNTExMFoYDzIxMjMwNjA2MDM1MTEwWjASMRAw
DgYDVQQDEwd6YS10ZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
xB8nQdo3yqd33BmkQ7P7ZvcnuVz4I6erqiDHfRDfbS2RvFV83gdGgD4TTd+yOwQV
t5Bt6ZYfC4GHxy77GWeAp72usDWdOmNFWQbSUBWLyz2wsI5hS36nxSdL8ztN2hm7
G4DGESOthdWJ0H3PNVzonz9v+eBeeVFLD2sXWKLpbsWWeF0uRj3Si+tIWspFANyb
8g3/raRGR7Rug3tlpH9HkP6KtMc3QwuHm8MDxWHDO3hKklFVsI4595oI7kmVYNPE
9xsuFoO4Jdr+/wS6eTR0Yt5lFFh7he0EI/VJCtKUj/MkkSuy77q0Iw9eSCPiaHZa
42xBKFU65KNKh9EHTvaEswIDAQABo00wSzAdBgNVHQ4EFgQUfnrmflVwOFc/okJE
vExsc2Vk3zgwHwYDVR0jBBgwFoAUOuljIiH+3u+tR+gZPqOOr4XYEXYwCQYDVR0T
BAIwADANBgkqhkiG9w0BAQsFAAOCAQEAl/bL654d2UgLx05/9lFZeCm6TIoeg2lN
qYjDfVJRwh97tooyGEmFn3z3Fwi3wlCmdA/i0tM6guT8U6N7XaEh38Xl5G2AriZb
REsV9Gd8JLXe7VvsDG2T+Cvw1SVz/d9aM+Rsfb7Bt/8X5aJLDZrYtKketA898/Kx
GoKO2glgwHpArOH9IjHSLxbpfLZqz2XH5+DLfy4Q77GRVagL5BxNAqU9wxc3rmUv
2zjl8t5kBEM7hhovQY9qgri8vE65olAHgPX7a4r1VfEfsCUkwykHjfduuCwJNgqz
jdvaAbjjn1LERYHyGBH99kHNu/jRLHhw59lxE4A5y/KfOAWVJWOdZw==
-----END CERTIFICATE-----
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment