当前位置:   article > 正文

【ES一】SpringBoot2.x+ES8.11.1(windows环境)整合_springboot集成es8.11

springboot集成es8.11

一、两种整合方式

目前有两种最常用的整合方式,一种是ElasticSearch官方提供的 Java High Level Rest Client,一种是Spring提供的 spring-boot-starter-data-elasticsearch 方式:

1.spring-boot-starter-data-elasticsearch 方式

  • 由 Spring 提供,是 Spring 在 ES 官方接口基础之上的二次封装,使用简单,易于上手;
  • 缺点是更新太慢,SpringBoot 2.2.x 才提供对 es7.x 的支持,版本关联性很大,不易维护;

2. Java High Level Rest Client 方式(推荐)我使用的)

  • 由ES官方提供,代码语法和DSL语法相似(即Json格式的ES操作语法);
  • 用法灵活,可以自由使用;
  • SpringBoot 和 ES 版本的关联性较小;

二、开始搭建

项目基础

1.SpringBoot3.x JDK17 Es8.11.1 ik分词 8.11.1(启动报错暂时放弃……)

2.SpringBoot2.x JDK17 Es8.11.1 ik分词 8.11.1(es_work)

windows环境

地址:C:\java\elasticsearch8111

JDK :ES_JAVA_HOME (JDK17.0.3)

前提了解

es与jdk版本对应:支持一览表 | Elastic

es与Spring Data Elasticsearch 之间版本对应:Spring Data Elasticsearch - Reference Documentation

步骤

1.安装ES

链接:win10+elasticsearch8.12 安装教程_win10 elasticsearch8.12-CSDN博客

下载地址:Elasticsearch 8.11.1 | Elastic

本地地址:C:\java\elasticsearch8111\elasticsearch-8.11.1

注意:环境变量JDK配置正常是JAVA_HOME,es配置里是ES_JAVA_HOME,启动时会报错,所以在环境变量里添加上ES_JAVA_HOM,如果你有其他方法也可以。

默认地址:localhost:9200

账号密码:账号:elastic 密码:自动生成(Sx6+sb3Ags45pNyrfws=),也可自定义。(忘记密码怎么办?进入es安装目录的bin文件中执行一下命令会返回最新的密码 命令 : elasticsearch-reset-password -u elastic)

2.安装ik分词

链接:本地elasticsearch中文分词器 ik分词器安装及使用_es安装ik分词器-CSDN博客

本地地址:C:\java\elasticsearch8111\elasticsearch-8.11.1\plugins\ik

IK分词器有两种分词模式:ik_max_word(最细粒度拆分)和ik_smart(最粗粒度)模式。

自定义分词bic文件:C:\java\elasticsearch8111\elasticsearch-8.11.1\plugins\ik\config

3.安装客户端Kibana

需要和es版本保持一致

默认地址:http://localhost:5601/   初次访问一般后边还有code拼接

账号密码:es的账号密码

本地地址:C:\java\elasticsearch8111\kibana-8.11.1-windows-x86_64\kibana-8.11.1

学习链接:ElasticSearch——Kibana Windows下的安装和Dev Tools的使用_elastic dev tools-CSDN博客

使用教程:ES8.8生产实践——数据查询与数据可视化(Kibana)_es可视化-CSDN博客

4.JAVA代码

pom.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.es</groupId>
  7. <artifactId>es-work</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <name>es-work</name>
  10. <packaging>jar</packaging>
  11. <parent>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-parent</artifactId>
  14. <version>2.4.4</version>
  15. </parent>
  16. <properties>
  17. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  18. <junit.version>5.9.1</junit.version>
  19. </properties>
  20. <dependencies>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-web</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-test</artifactId>
  28. <scope>test</scope>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.projectlombok</groupId>
  32. <artifactId>lombok</artifactId>
  33. <version>1.18.20</version>
  34. </dependency>
  35. <!-- @ConfigurationProperties(prefix = "elasticsearch") 注解依赖 -->
  36. <dependency>
  37. <groupId>org.springframework.boot</groupId>
  38. <artifactId>spring-boot-configuration-processor</artifactId>
  39. <optional>true</optional>
  40. </dependency>
  41. <!-- 若不存在Spring Data ES的某个版本支持你下的ES版本,则使用 -->
  42. <!-- ES 官方提供的在JAVA环境使用的依赖 -->
  43. <dependency>
  44. <groupId>co.elastic.clients</groupId>
  45. <artifactId>elasticsearch-java</artifactId>
  46. <version>8.11.1</version>
  47. </dependency>
  48. <!-- 和第一个依赖是一起的,为了解决springboot项目的兼容性问题 -->
  49. <dependency>
  50. <groupId>com.fasterxml.jackson.core</groupId>
  51. <artifactId>jackson-databind</artifactId>
  52. </dependency>
  53. <!-- 原来只有前两依赖,但是启动报错找不到依赖,要注意版本号是否兼容 -->
  54. <dependency>
  55. <groupId>jakarta.json</groupId>
  56. <artifactId>jakarta.json-api</artifactId>
  57. <version>2.0.1</version>
  58. </dependency>
  59. <!-- es的客户端,连接,版本号要与ES一致 -->
  60. <dependency>
  61. <groupId>org.elasticsearch.client</groupId>
  62. <artifactId>elasticsearch-rest-client</artifactId>
  63. <version>8.11.1</version>
  64. </dependency>
  65. <!-- lombok -->
  66. <dependency>
  67. <groupId>org.projectlombok</groupId>
  68. <artifactId>lombok</artifactId>
  69. </dependency>
  70. </dependencies>
  71. </project>
application.yml
  1. server:
  2. port: 8092
  3. spring:
  4. # elasticsearch配置
  5. elasticsearch:
  6. # 自定义属性---设置是否开启ES,false表不开窍ES
  7. open: true
  8. # es集群名称,如果下载es设置了集群名称,则使用配置的集群名称
  9. clusterName: es
  10. hosts: 127.0.0.1:9200
  11. # es 请求方式
  12. scheme: http
  13. # es 连接超时时间
  14. connectTimeOut: 1000
  15. # es socket 连接超时时间
  16. socketTimeOut: 30000
  17. # es 请求超时时间
  18. connectionRequestTimeOut: 500
  19. # es 最大连接数
  20. maxConnectNum: 100
  21. # es 每个路由的最大连接数
  22. maxConnectNumPerRoute: 100
  23. userName: elastic
  24. password: Sx6+sb3Ags45pNyrfws=
config
  1. package com.es.eswork.config;
  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 lombok.Data;
  7. import org.apache.http.HttpHost;
  8. import org.apache.http.auth.AuthScope;
  9. import org.apache.http.auth.UsernamePasswordCredentials;
  10. import org.elasticsearch.client.RestClient;
  11. import org.elasticsearch.client.RestClientBuilder;
  12. import org.springframework.boot.context.properties.ConfigurationProperties;
  13. import org.springframework.context.annotation.Bean;
  14. import org.springframework.context.annotation.Configuration;
  15. import org.apache.http.client.CredentialsProvider;
  16. import org.apache.http.impl.client.BasicCredentialsProvider;
  17. @Data
  18. @Configuration
  19. @ConfigurationProperties(prefix = "elasticsearch")
  20. public class ElasticSearchConfig {
  21. // 是否开启ES
  22. private Boolean open;
  23. // es 集群host ip 地址
  24. private String hosts;
  25. // es用户名
  26. private String userName;
  27. // es密码
  28. private String password;
  29. // es 请求方式
  30. private String scheme;
  31. // es集群名称
  32. private String clusterName;
  33. // es 连接超时时间
  34. private int connectTimeOut;
  35. // es socket 连接超时时间
  36. private int socketTimeOut;
  37. // es 请求超时时间
  38. private int connectionRequestTimeOut;
  39. // es 最大连接数
  40. private int maxConnectNum;
  41. // es 每个路由的最大连接数
  42. private int maxConnectNumPerRoute;
  43. // es api key
  44. private String apiKey;
  45. public RestClientBuilder creatBaseConfBuilder(String scheme){
  46. // 1. 单节点ES Host获取
  47. String host = hosts.split(":")[0];
  48. String port = hosts.split(":")[1];
  49. // The value of the schemes attribute used bynoSafeRestClient() is http
  50. // but The value of the schemes attribute used by safeRestClient() is https
  51. HttpHost httpHost = new HttpHost(host, Integer.parseInt(port),scheme);
  52. // 1.1 设置用户名和密码(账号密码连接,xpack.security.enabled: true)
  53. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  54. credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
  55. // 2. 创建构建器对象
  56. //RestClientBuilder: ES客户端库的构建器接口,用于构建RestClient实例;允许你配置与Elasticsearch集群的连接,设置请求超时,设置身份验证,配置代理等
  57. RestClientBuilder builder = RestClient.builder(httpHost);
  58. // 连接延时配置
  59. builder.setRequestConfigCallback(requestConfigBuilder -> {
  60. requestConfigBuilder.setConnectTimeout(connectTimeOut);
  61. requestConfigBuilder.setSocketTimeout(socketTimeOut);
  62. requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);
  63. return requestConfigBuilder;
  64. });
  65. // 3. HttpClient 连接数配置
  66. builder.setHttpClientConfigCallback(httpClientBuilder -> {
  67. httpClientBuilder.setMaxConnTotal(maxConnectNum);
  68. httpClientBuilder.setMaxConnPerRoute(maxConnectNumPerRoute);
  69. httpClientBuilder.disableAuthCaching(); // 1.1.1 设置账号密码
  70. httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
  71. return httpClientBuilder;
  72. });
  73. return builder;
  74. }
  75. /**
  76. * @function: 创建使用http连接来直接连接ES服务器的客户端
  77. * 如果@Bean没有指定bean的名称,那么这个bean的名称就是方法名
  78. */
  79. @Bean
  80. public ElasticsearchClient elasticsearchClient(){
  81. RestClientBuilder builder = creatBaseConfBuilder((scheme == "http")?"http":"http");
  82. //Create the transport with a Jackson mapper
  83. ElasticsearchTransport transport = new RestClientTransport(builder.build(), new JacksonJsonpMapper());
  84. //And create the API client
  85. ElasticsearchClient esClient = new ElasticsearchClient(transport);
  86. return esClient;
  87. }
  88. }
test测试
  1. package com.es.eswork;
  2. import com.es.eswork.entity.User;
  3. import com.es.eswork.utils.ElasticsearchHandle;
  4. import lombok.extern.slf4j.Slf4j;
  5. import net.minidev.json.JSONArray;
  6. import org.junit.jupiter.api.Test;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.boot.test.context.SpringBootTest;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. @SpringBootTest
  12. @Slf4j
  13. public class EsTestByUtil {
  14. @Autowired
  15. ElasticsearchHandle client;
  16. @Test
  17. public void test() {
  18. //测试logstash
  19. log.info("log");
  20. String indexName = "test_index";
  21. try {
  22. boolean b = client.hasIndex(indexName);
  23. System.out.println(b);
  24. } catch (IOException e) {
  25. throw new RuntimeException(e);
  26. }
  27. }
  28. @Test
  29. public void search() {
  30. List<User> search = client.search("test_index", "hello", 5, "name");
  31. System.out.println(JSONArray.toJSONString(search));
  32. }
  33. @Test
  34. public void searchCategoryIds() {
  35. List<String> ca = new ArrayList<>();
  36. ca.add("hello");
  37. List<User> search = client.searchCategoryIds("test_index", "hello", ca, 5);
  38. System.out.println(JSONArray.toJSONString(search));
  39. }
  40. }
utils
  1. package com.es.eswork.utils;
  2. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  3. import co.elastic.clients.elasticsearch._types.FieldValue;
  4. import co.elastic.clients.elasticsearch._types.mapping.Property;
  5. import co.elastic.clients.elasticsearch._types.query_dsl.Query;
  6. import co.elastic.clients.elasticsearch._types.query_dsl.TermsQuery;
  7. import co.elastic.clients.elasticsearch._types.query_dsl.TermsQueryField;
  8. import co.elastic.clients.elasticsearch.core.DeleteResponse;
  9. import co.elastic.clients.elasticsearch.core.GetResponse;
  10. import co.elastic.clients.elasticsearch.core.IndexResponse;
  11. import co.elastic.clients.elasticsearch.core.SearchResponse;
  12. import co.elastic.clients.elasticsearch.core.search.Hit;
  13. import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
  14. import co.elastic.clients.elasticsearch.indices.DeleteIndexResponse;
  15. import co.elastic.clients.transport.endpoints.BooleanResponse;
  16. import com.es.eswork.entity.User;
  17. import lombok.extern.slf4j.Slf4j;
  18. import org.apache.commons.lang3.StringUtils;
  19. import org.springframework.beans.factory.annotation.Autowired;
  20. import org.springframework.stereotype.Component;
  21. import java.io.IOException;
  22. import java.util.ArrayList;
  23. import java.util.List;
  24. import java.util.Map;
  25. @Slf4j
  26. @Component
  27. public class ElasticsearchHandle {
  28. @Autowired
  29. private ElasticsearchClient client;
  30. /**
  31. * 判断索引是否存在
  32. *
  33. * @param indexName
  34. * @return
  35. * @throws IOException
  36. */
  37. public boolean hasIndex(String indexName) throws IOException {
  38. BooleanResponse exists = client.indices().exists(d -> d.index(indexName));
  39. return exists.value();
  40. }
  41. /**
  42. * 删除索引
  43. *
  44. * @param indexName
  45. * @throws IOException
  46. */
  47. public boolean deleteIndex(String indexName) throws IOException {
  48. DeleteIndexResponse response = client.indices().delete(d -> d.index(indexName));
  49. return true;
  50. }
  51. /**
  52. * 创建索引
  53. *
  54. * @param indexName
  55. * @return
  56. * @throws IOException
  57. */
  58. public boolean createIndex(String indexName) {
  59. try {
  60. CreateIndexResponse indexResponse = client.indices().create(c -> c.index(indexName));
  61. } catch (IOException e) {
  62. log.error("索引创建失败:{}", e.getMessage());
  63. // throw new ExploException(HttpCode.INDEX_CREATE_ERROR, "创建索引失败");
  64. }
  65. return true;
  66. }
  67. /**
  68. * 创建索引,不允许外部直接调用
  69. *
  70. * @param indexName
  71. * @param mapping
  72. * @throws IOException
  73. */
  74. private boolean createIndex(String indexName, Map<String, Property> mapping) throws IOException {
  75. CreateIndexResponse createIndexResponse = client.indices().create(c -> {
  76. c.index(indexName).mappings(mappings -> mappings.properties(mapping));
  77. return c;
  78. });
  79. return createIndexResponse.acknowledged();
  80. }
  81. /**
  82. * 重新创建索引,如果已存在先删除
  83. *
  84. * @param indexName
  85. * @param mapping
  86. */
  87. public void reCreateIndex(String indexName, Map<String, Property> mapping) {
  88. try {
  89. if (this.hasIndex(indexName)) {
  90. this.deleteIndex(indexName);
  91. }
  92. } catch (IOException e) {
  93. e.printStackTrace();
  94. log.error("删除索引失败:{}", e.getMessage());
  95. // throw new ExploException(HttpCode.INDEX_DELETE_ERROR, "删除索引失败");
  96. }
  97. try {
  98. this.createIndex(indexName, mapping);
  99. } catch (IOException e) {
  100. e.printStackTrace();
  101. log.error("重新创建索引失败:{}", e.getMessage());
  102. //throw new ExploException(HttpCode.INDEX_CREATE_ERROR, "重新创建索引失败");
  103. }
  104. }
  105. /**
  106. * 新增数据
  107. *
  108. * @param indexName
  109. * @throws IOException
  110. */
  111. public boolean insertDocument(String indexName, Object obj, String id) {
  112. try {
  113. IndexResponse indexResponse = client.index(i -> i
  114. .index(indexName)
  115. .id(id)
  116. .document(obj));
  117. return true;
  118. } catch (IOException e) {
  119. log.error("数据插入ES异常:{}", e.getMessage());
  120. // throw new ExploException(HttpCode.ES_INSERT_ERROR, "ES新增数据失败");
  121. }
  122. return false;
  123. }
  124. /**
  125. * 查询数据
  126. *
  127. * @param indexName
  128. * @param id
  129. * @return
  130. */
  131. public GetResponse<User> searchDocument(String indexName, String id) {
  132. try {
  133. GetResponse<User> getResponse = client.get(g -> g
  134. .index(indexName)
  135. .id(id)
  136. , User.class
  137. );
  138. return getResponse;
  139. } catch (IOException e) {
  140. log.error("查询ES异常:{}", e.getMessage());
  141. // throw new ExploException(HttpCode.ES_SEARCH_ERROR, "查询ES数据失败");
  142. }
  143. return null;
  144. }
  145. /**
  146. * 删除数据
  147. *
  148. * @param indexName
  149. * @param id
  150. * @return
  151. */
  152. public boolean deleteDocument(String indexName, String id) {
  153. try {
  154. DeleteResponse deleteResponse = client.delete(d -> d
  155. .index(indexName)
  156. .id(id)
  157. );
  158. } catch (IOException e) {
  159. log.error("删除Es数据异常:{}", e.getMessage());
  160. //throw new ExploException(HttpCode.ES_DELETE_ERROR, "数据删除失败");
  161. }
  162. return true;
  163. }
  164. /**
  165. *
  166. * 查询满足条件的数据 --User表
  167. * @param indexName 为索引名称
  168. * @param query 查询的内容
  169. * @param top 查询条数
  170. * @param field 参数
  171. * @return
  172. */
  173. public List<User> search(String indexName, String query, int top,String field) {
  174. List<User> documentParagraphs = new ArrayList<>();
  175. try {
  176. SearchResponse<User> search = client.search(s -> s
  177. .index(indexName)
  178. .query(q -> q
  179. .match(t -> t
  180. .field(field)
  181. .query(query)
  182. ))
  183. .from(0)
  184. .size(top)
  185. .highlight(h -> h
  186. .fields("name", f -> f
  187. .preTags("<em>")
  188. .postTags("</em>")
  189. )
  190. )
  191. // .sort(f -> f.field(o -> o.field("docId").order(SortOrder.Desc)))
  192. , User.class
  193. );
  194. for (Hit<User> hit : search.hits().hits()) {
  195. //User user = hit.source();
  196. User user = highLight(hit);
  197. documentParagraphs.add(user);
  198. }
  199. } catch (IOException e) {
  200. log.error("查询ES异常:{}", e.getMessage());
  201. // throw new ExploException(HttpCode.ES_SEARCH_ERROR, "查询ES数据失败");
  202. }
  203. return documentParagraphs;
  204. }
  205. /**
  206. * 高亮数据提取
  207. */
  208. private User highLight(Hit<User> hit) {
  209. User paragraph = hit.source();
  210. try {
  211. Map<String, List<String>> highlight = hit.highlight();
  212. List<String> list = highlight.get("name");
  213. String join = StringUtils.join(list, "");
  214. if (StringUtils.isNotBlank(join)) {
  215. paragraph.setName(join);
  216. // paragraph.setAge(hit.score());
  217. }
  218. } catch (Exception e) {
  219. log.error("获取ES高亮数据异常:{}", e.getMessage());
  220. }
  221. return paragraph;
  222. }
  223. // /**
  224. // *解析高亮数据
  225. // */
  226. // Map<String, List<String>> highlight = hit.highlight();
  227. // List<String> list = highlight.get("name");
  228. // String join = StringUtils.join(list, "");
  229. // if (StringUtils.isNotBlank(join)) {
  230. // paragraph.setContent(join);
  231. // }
  232. public List<User> searchCategoryIds(String indexName, String query, List<String> categoryId,int top) {
  233. List<User> documentParagraphs = new ArrayList<>();
  234. List<FieldValue> values = new ArrayList<>();
  235. for (String id : categoryId) {
  236. values.add(FieldValue.of(id));
  237. }
  238. Query categoryQuery = TermsQuery.of(t -> t.field("name.keyword").terms(new TermsQueryField.Builder()
  239. .value(values).build()
  240. ))._toQuery();
  241. try {
  242. SearchResponse<User> search = client.search(s -> s
  243. .index(indexName)
  244. .query(q -> q
  245. .bool(b -> b
  246. .must(categoryQuery
  247. )
  248. .should(sh -> sh
  249. .match(t -> t
  250. .field("name")
  251. .query(query)
  252. )
  253. )
  254. )
  255. )
  256. .highlight(h -> h
  257. .fields("name", f -> f
  258. .preTags("<em>")
  259. .postTags("</em>")
  260. )
  261. )
  262. .from(0)
  263. .size(top)
  264. , User.class
  265. );
  266. for (Hit<User> hit : search.hits().hits()) {
  267. User pd = hit.source();
  268. documentParagraphs.add(pd);
  269. }
  270. } catch (IOException e) {
  271. log.error("查询ES异常:{}", e.getMessage());
  272. // throw new ExploException(HttpCode.ES_SEARCH_ERROR, "查询ES数据失败");
  273. }
  274. return documentParagraphs;
  275. }
  276. /**
  277. * 高亮数据提取
  278. // */
  279. // private DocumentParagraph highLight(Hit<DocumentParagraph> hit) {
  280. // DocumentParagraph paragraph = hit.source();
  281. // try {
  282. // Map<String, List<String>> highlight = hit.highlight();
  283. // List<String> list = highlight.get("content");
  284. // String join = StringUtils.join(list, "");
  285. // if (StringUtils.isNotBlank(join)) {
  286. // paragraph.setContent(join);
  287. // paragraph.setScore(hit.score());
  288. //
  289. // }
  290. // } catch (Exception e) {
  291. // log.error("获取ES高亮数据异常:{}", e.getMessage());
  292. // }
  293. // return paragraph;
  294. // }
  295. // /**
  296. // *解析高亮数据
  297. // */
  298. // Map<String, List<String>> highlight = hit.highlight();
  299. // List<String> list = highlight.get("content");
  300. // String join = StringUtils.join(list, "");
  301. // if (StringUtils.isNotBlank(join)) {
  302. // paragraph.setContent(join);
  303. // }
  304. }

5. 过程中遇见的问题

5.1 项目启动时异常,pom依赖缺少

  (原文章中只有前两个依赖,上边代码已添加)

  1. <!-- 若不存在Spring Data ES的某个版本支持你下的ES版本,则使用 -->
  2. <!-- ES 官方提供的在JAVA环境使用的依赖 -->
  3. <dependency>
  4. <groupId>co.elastic.clients</groupId>
  5. <artifactId>elasticsearch-java</artifactId>
  6. <version>8.11.1</version>
  7. </dependency>
  8. <!-- 和第一个依赖是一起的,为了解决springboot项目的兼容性问题 -->
  9. <dependency>
  10. <groupId>com.fasterxml.jackson.core</groupId>
  11. <artifactId>jackson-databind</artifactId>
  12. </dependency>
  13. <!-- 原来只有前两依赖,但是启动报错找不到依赖,要注意版本号是否兼容 -->
  14. <dependency>
  15. <groupId>jakarta.json</groupId>
  16. <artifactId>jakarta.json-api</artifactId>
  17. <version>2.0.1</version>
  18. </dependency>
  19. <!-- es的客户端,连接,版本号要与ES一致 -->
  20. <dependency>
  21. <groupId>org.elasticsearch.client</groupId>
  22. <artifactId>elasticsearch-rest-client</artifactId>
  23. <version>8.11.1</version>
  24. </dependency>
5.2 密码连接Es时 

     项目启动后,测试向es新建索引

5.2.1 报错Connet 超时
        原因是是因为开启了 ssl 认证。

        elasticsearch.yml 配置 xpack.security.http.ssl: enabled: false(true改成false)

5.2.2 报错 missing authentication credentials for REST…

        [es/indices.create] failed: [security_exception] missing authentication credentials for REST request [/direct_connect…

        因为设置了账号密码链接,但是config类未配置账号密码,原学习文章未包含以下代码,需在ElasticSearchConfig.class 中加上 1.1 和 1.1.1 配置(上边代码已添加)

  1. // 1.1 设置用户名和密码 (账号密码连接,xpack.security.enabled: true)
  2. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  3. credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
  4. // 3. HttpClient 连接数配置
  5. builder.setHttpClientConfigCallback(httpClientBuilder -> {
  6. httpClientBuilder.setMaxConnTotal(maxConnectNum);
  7. httpClientBuilder.setMaxConnPerRoute(maxConnectNumPerRoute);
  8. httpClientBuilder.disableAuthCaching(); // 1.1.1 设置账号密码
  9. httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
  10. return httpClientBuilder;
  11. });
5.3 Kibana 启动报错

        Unable to retrieve version information from Elasticsearch nodes. write EPROTO 18300000:error:0A00010B:SSL routines:ssl3_get_record:wrong version ……

1、不能使用localhost,需要使用私有IP。将Kibana.yml中的elasticsearch.hosts以及elasticsearch.yml中的network.host、discovery.seed_hosts都使用私有IP后,问题解决。

原文链接:[疑难杂症]Kibana报错:Unable to retrieve version information from Elasticsearch nodes-CSDN博客

2、elasticsearch.hosts: ['http://10.24.18.94:9200'] 注意这个地址,可能原来是es.yml配置(目录4.2.1)问题,链接方式成https了,改成http。

ES Elasticsearch.yml的xpack.security.http.ssl.enabled:

● 默认true:

        必须使用https://localhost:9200/访问ES服务+启动Kibana服务会成功+需要使用账号连接+必须使用HTTPS连接

● 若为false:

        必须使用http://localhost:9200/访问ES服务+启动Kibana服务会失败+需要使用账号连接,但必须使用HTTP连接

学习链接:【ElasticSearch8】SpringBoot集成ElasticSearch8.x 基本应用 CRUD操作 环境安装-CSDN博客

SpringBoot集成Elasticsearch8.x(7)|(新版本Java API Client使用完整示例)_springboot集成elasticsearch8.xapi-CSDN博客

三、使用 Logstash 同步海量 MySQL 数据到 ES

待补充…………

总结

| 把学习过程中,使用到的各位优秀博主文章整理到一起,做笔记,并分享。有问题欢迎指出。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/649668
推荐阅读
相关标签
  

闽ICP备14008679号