12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- package com.wtkj.config.es;
- 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.HttpHost;
- import org.elasticsearch.client.RestClient;
- import org.elasticsearch.client.RestClientBuilder;
- import org.elasticsearch.client.RestHighLevelClient;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.util.StringUtils;
- /**
- * @author Blizzard
- * @create at 2023-09-27 10:03
- * @describe
- */
- @Configuration
- public class EsConfig {
- @Value("${spring.elasticsearch.rest.uris}")
- private String hosts;
- private HttpHost[] toHttpHost() {
- if (!StringUtils.hasLength(hosts)) {
- throw new RuntimeException("invalid elasticsearch configuration. elasticsearch.hosts不能为空!");
- }
- // 多个IP逗号隔开
- 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]), "http");
- httpHosts[i] = httpHost;
- }
- return httpHosts;
- }
- @Bean
- public ElasticsearchClient elasticsearchClient() {
- HttpHost[] httpHost = toHttpHost();
- RestClient restClient = RestClient.builder(httpHost).build();
- // Create the transport with a Jackson mapper
- ElasticsearchTransport transport = new RestClientTransport(
- restClient, new JacksonJsonpMapper());
- // And create the API client
- return new ElasticsearchClient(transport);
- }
- @Bean
- public RestHighLevelClient esRestClient() {
- RestClientBuilder builder;
- builder = RestClient.builder(toHttpHost());
- return new RestHighLevelClient(builder);
- }
- }
|