EsConfig.java 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package com.wtkj.config.es;
  2. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  3. import co.elastic.clients.json.jackson.JacksonJsonpMapper;
  4. import co.elastic.clients.transport.ElasticsearchTransport;
  5. import co.elastic.clients.transport.rest_client.RestClientTransport;
  6. import org.apache.http.HttpHost;
  7. import org.elasticsearch.client.RestClient;
  8. import org.elasticsearch.client.RestClientBuilder;
  9. import org.elasticsearch.client.RestHighLevelClient;
  10. import org.springframework.beans.factory.annotation.Value;
  11. import org.springframework.context.annotation.Bean;
  12. import org.springframework.context.annotation.Configuration;
  13. import org.springframework.util.StringUtils;
  14. /**
  15. * @author Blizzard
  16. * @create at 2023-09-27 10:03
  17. * @describe
  18. */
  19. @Configuration
  20. public class EsConfig {
  21. @Value("${spring.elasticsearch.rest.uris}")
  22. private String hosts;
  23. private HttpHost[] toHttpHost() {
  24. if (!StringUtils.hasLength(hosts)) {
  25. throw new RuntimeException("invalid elasticsearch configuration. elasticsearch.hosts不能为空!");
  26. }
  27. // 多个IP逗号隔开
  28. String[] hostArray = hosts.split(",");
  29. HttpHost[] httpHosts = new HttpHost[hostArray.length];
  30. HttpHost httpHost;
  31. for (int i = 0; i < hostArray.length; i++) {
  32. String[] strings = hostArray[i].split(":");
  33. httpHost = new HttpHost(strings[0], Integer.parseInt(strings[1]), "http");
  34. httpHosts[i] = httpHost;
  35. }
  36. return httpHosts;
  37. }
  38. @Bean
  39. public ElasticsearchClient elasticsearchClient() {
  40. HttpHost[] httpHost = toHttpHost();
  41. RestClient restClient = RestClient.builder(httpHost).build();
  42. // Create the transport with a Jackson mapper
  43. ElasticsearchTransport transport = new RestClientTransport(
  44. restClient, new JacksonJsonpMapper());
  45. // And create the API client
  46. return new ElasticsearchClient(transport);
  47. }
  48. @Bean
  49. public RestHighLevelClient esRestClient() {
  50. RestClientBuilder builder;
  51. builder = RestClient.builder(toHttpHost());
  52. return new RestHighLevelClient(builder);
  53. }
  54. }