问题描述
这里给初学es出现java连接异常报错的小白们一些建议,大佬如果出现了相似bug,请看看其博主文章
学习es(elasticsearch)的时候,发现无法连接配置好的es数据库,检查yml文件,端口号,虚拟机ip全部都是正确的,然而run的时候报如下错误
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2024-03-26 00:08:27.485 ERROR 10932 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productRepository' defined in com.mytest.repository.ProductRepository defined in @EnableElasticsearchRepositories declared on ElasticsearchRepositoriesRegistrar.EnableElasticsearchRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is org.springframework.data.elasticsearch.UncategorizedElasticsearchException: java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [/192.168.87.100:9200]; nested exception is ElasticsearchException[java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [/192.168.87.100:9200]]; nested: ExecutionException[java.net.ConnectException: Timeout connecting to [/192.168.87.100:9200]]; nested: ConnectException[Timeout connecting to [/192.168.87.100:9200]];
网上解决方案很多很杂,这里给一个比较简单的方法,仅供参考
原因分析:
在一堆的嵌套异常中,得找到最后面的报错,我发现了重点,也就是
ExecutionException[java.net.ConnectException: Timeout connecting to [/192.168.87.100:9200]]; nested: ConnectException[Timeout connecting to [/192.168.87.100:9200]];
idea配置文件检查正确之后,linux查看服务启动状态,都是正确的,那么一定是es的配置文件或者linux内存配置出了问题
解决方案:
在查询资料之后,有三处配置需要配置
(1) es服务在linux上无法启动解决方案:限制最大文件数,打开
vim /etc/sysctl.conf
添加以下配置:
vm.max_map_count=655360
让配置生效:
sysctl -p
(2)外部无法访问ES的解决方案:打开Elasticsearch安装路径下config目录下的elasticsearch.yml文件,加入如下配置:
discovery.seed_hosts: ["host1"]
#允许任意ip都可以访问
network.host: 0.0.0.0
备注:因为这个配置文件是yml文件,请小伙伴们注意空格,yml文件的格式
(3) 如果仍然无法连接,查看es服务,如果有如下报错
max file descriptors [4096] for elasticsearch process is too low, increase to at least [65536]
解决方案:
vim /etc/security/limits.conf
在末尾添加以下内容;
* soft nofile 65536
* hard nofile 65536
* soft nproc 4096
* hard nproc 4096
然后:wq 保存退出
切换到普通用户,备注:es 和可视化kibana都不能用root用户去启动
su [用户名]
然后找到你的elasticsearch目录下的bin,执行启动指令
./elasticsearch
再启动自己的springboot服务,启动成功。
无论是原生java采用maven引入坐标的形式,还是springboot去启动es,都可以解决es连接失败异常的问题