1.加入依赖
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.12.2</version>
</dependency>
2.配置类
@Slf4j
@Configuration
public class ElasticSearchConfig {
@Value("${elasticsearch.hosts}")
private String hosts;
@Value("${elasticsearch.port}")
private int port;
@Value("${elasticsearch.username}")
private String username;
@Value("${elasticsearch.password}")
private String password;
@Value("${elasticsearch.apikey:''}")
private String apikey;
/**
* 单节点没密码连接
*
* @return
*/
@Bean
public ElasticsearchClient elasticsearchClient() {
String[] servers = hosts.split(",");
int len = servers.length;
if (0 == len) {
log.error("ElasticsearchClient 配置错误!");
}
ElasticsearchTransport transport = null;
// 不是集群时
if (1 == len) {
// 无账号、密码
if (StringUtils.isEmpty(username) && StringUtils.isEmpty(password)) {
RestClient client = RestClient.builder(new HttpHost(servers[0], port, "http"))
.setHttpClientConfigCallback(httpClientBuilder
->httpClientBuilder.setDefaultHeaders(
Collections.singletonList(new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString())))
.addInterceptorLast((HttpResponseInterceptor) (response, context)
-> response.addHeader("X-Elastic-Product", "Elasticsearch")))
.build();
transport = new RestClientTransport(client, new JacksonJsonpMapper());
} else {
// 账号密码的配置
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
// 自签证书的设置,并且还包含了账号密码
RestClientBuilder.HttpClientConfigCallback callback = httpAsyncClientBuilder -> httpAsyncClientBuilder
.setDefaultCredentialsProvider(credentialsProvider)
.addInterceptorLast(
(HttpResponseInterceptor)
(response, context) ->
response.addHeader("X-Elastic-Product", "Elasticsearch"));
RestClient client = RestClient.builder(new HttpHost(servers[0], port, "http"))
.setHttpClientConfigCallback(callback)
.build();
transport = new RestClientTransport(client, new JacksonJsonpMapper());
}
} else {
// 集群时无账号、密码
if (StringUtils.isEmpty(username) && StringUtils.isEmpty(password)) {
transport = getElasticsearchTransport(toHttpHost());
} else {
transport = getElasticsearchTransport(username, password, toHttpHost());
}
}
return new ElasticsearchClient(transport);
}
private HttpHost[] toHttpHost() {
if (hosts.split(",").length == 0) {
throw new RuntimeException("invalid elasticsearch configuration");
}
String[] hostArray = hosts.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]), &#