1.前言
2020年03月09日写过一篇SpringBoot2.x集成分布式搜索引擎Elasticsearch的文章。最近针对项目使用的spring boot版本进行了升级,升级至3.0.5。依照官方文档描述,需要使用8.5.3版本的elasticsearch服务。于是就按照Installing Elasticsearch with Docker文档进行服务安装,安装到使用的过程中遇到了一系列问题,比如使用http方式无法访问elasticsearch服务、spring boot通过https方式连接elasticsearch出现程序报错、spring boot集成elasticseach相关类被弃用等。因此希望通过写文章的方式对过程进行一个巩固、总结,同时也希望对有需要的小伙伴提供一点帮助。
2. 安装elasticsearch
本文会采用docker方式来安装elasticsearch,为了方便kibana连接elasticsearch,会先创一个桥接网络
2.1 创建桥接网络
docker network create elastic
2.2 拉取elasticsearch镜像
docker pull docker.elastic.co/elasticsearch/elasticsearch:8.7.0
2.3 运行容器
docker run --name es-node01 --net elastic -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -t docker.elastic.co/elasticsearch/elasticsearch:8.7.0
容器成功运行后,终端会打印出如下内容:
- 访问
elasticsearch对应的用户名、密码 kibana连接elasticsearch对应的token- 集群新增节点对应的
token
2.4 命令行方式访问
想要通过命令行访问elasticsearch,需要将容器中生成的证书拷贝到宿主机
docker cp es-node01:/usr/share/elasticsearch/config/certs/http_ca.crt .
有了证书,可以通过如下方式进行访问
curl --cacert http_ca.crt -u elastic https://localhost:9200
输入完命令后,终端会提示让输入密码,只需要将2.3步骤生成的密码粘贴即可得到访问结果
2.5 浏览器方式访问
在浏览器中输入http://localhost:9200/,得到的是该网页无法正常运作提示。出现这种情况的原因是高版本elasticsearch更注重安全性,需要用户通过https方式进行访问。当在浏览器中输入https://localhost:9200/,会提示您的连接不是私密连接,只需点击高级、继续前往即可
点击继续前往后,提示输入用户名、密码,只需将2.3步骤生成的信息贴入就可以得到访问结果
2.6 重置密码
当你再次访问elasticsearch,发现自己并没有对2.3步骤生成的密码进行存储,此时你也不必太惊慌,只需通过如下方式就可以实现密码重置
docker exec -it es-node01 /usr/share/elasticsearch/bin/elasticsearch-reset-password -u elastic
2.7 重置kibana连接token
当出现忘记token或者token过期的情况,可以通过如下命令来重置token
docker exec -it es-node01 /usr/share/elasticsearch/bin/elasticsearch-create-enrollment-token -s kibana
3. 安装kibana
基于调试需求,我们需要安装kibana
3.1 拉取镜像
docker exec -it es-node01 /usr/share/elasticsearch/bin/elasticsearch-create-enrollment-token -s kibana
3.2 启动容器
docker run --name kib-01 --net elastic -p 5601:5601 docker.elastic.co/kibana/kibana:8.7.0
3.3 点击链接
容器启动成功后会打印出跳转链接,点击链接会跳转到浏览器
在浏览器窗口中输入2.3章节生成的enrollment token
3.4 登录
kibana配置完成后会进入登录界面,只需要输入2.3步骤生成的用户名:elastic和密码即可
4.springBoot3.0.5连接elasticsearch
elasticsearch服务安装成功后,总想通过程序实现个小demo,以此来满足内心对技术追求的欲望
4.1 编写配置文件
spring:
elasticsearch:
uris: https://localhost:9200 # 指明es地址
username: elastic
password: +kDXDenCEo2shDeqwoSa
配置文件中的链接地址一定要使用
https方式
4.2 意料之外的报错
程序启动后,出乎意料的会出现一堆报错内容
org.springframework.dao.DataAccessResourceFailureException: PKIX path validation failed: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors
Caused by: java.lang.RuntimeException: PKIX path validation failed: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors
4.3 解决报错问题
为了解决上面的报错问题,我们需要将2.4步骤拷贝到宿主机的证书导入到jdk中
4.3.1 进入security目录
cd xxxxxx/Java/JavaVirtualMachines/azul-17.0.6/Contents/Home/lib/security
4.3.2 导入证书
keytool -keystore cacerts -importcert -alias "es_http_ca" -file xxxxxx/http_ca.crt
注意:一定要进入xxxxxx/Java/JavaVirtualMachines/azul-17.0.6/Contents/Home/lib/security目录,再进行证书导入
4.4 示例代码
最新示例代码可参考:boot-example-elasticsearch