首先,看服务器日志,主要就是一句话:

java.io.IOException: Too many open files

完整的如下:

Jul 03, 2019 1:42:28 PM io.netty.channel.DefaultChannelPipeline onUnhandledInboundException 
WARNING: An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception. 
java.io.IOException: Too many open files 
	at sun.nio.ch.ServerSocketChannelImpl.accept0(Native Method) 
	at sun.nio.ch.ServerSocketChannelImpl.accept(ServerSocketChannelImpl.java:422) 
	at sun.nio.ch.ServerSocketChannelImpl.accept(ServerSocketChannelImpl.java:250) 
	at io.netty.channel.socket.nio.NioServerSocketChannel.doReadMessages(NioServerSocketChannel.java:135) 
	at io.netty.channel.nio.AbstractNioMessageChannel$NioMessageUnsafe.read(AbstractNioMessageChannel.java:75) 
	at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:563) 
	at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:504) 
	at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:418) 
	at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:385) 
	at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:742) 
	at java.lang.Thread.run(Thread.java:748)

字面意思,就是打开的文件太多了,服务器着不住了。他handle不了啦。

然后,查询之后,别的都说是打开的“句柄”太多,哦霍,咱也不知道啥是句柄。

咱就说一下,我这是为啥出了上面的提示信息吧。

大师兄

大师兄

罪魁祸首,就是上面的一行代码

因为每次请求之后,都会走上面的这个方法,然后呢,这个方法每次都会去创建一个 elastic search的连接,

这个连接呢,就像是数据库的连接一样,你每次都弄一个,然后,一个进程允许的连接数估计是有限个的。然后,最后就到上限了,而且,创建的连接多了,也不关闭,一直创建,内存也就被吃完了。

为啥呢?

因为是,写代码的小老弟没这个概念呗。

觉得这个小模块,也不需要啥设计,就是啪啪啪一通复制粘贴稍加改动

丢丢丢,代码正常运行,哎,结果符合预期。OK,我的任务完了。怡然自得。小case。

哎,这就是“无知者无畏”。

应该怎么改呢?

大师兄

单例模式了解一下。标准的。

扩展

好好再学习一下:

1,什么是“单例模式”

我估计当年老师讲的跟上面的还是有点不一样的,比如,volatile老师估计就给你略过了吧。

单例模式的四种实现--应该是你见过的最全的单例模式实现啦

2,什么时候使用“单例模式”

就比如这个数据库连接,不管是连elastic search 还是mongo db 还是xxx db 等。 这些个连接,在系统中,没啥特殊要求,一个就够了,所以,以后再遇到类似的问题呢,咱不能也是啪啪啪一通复制粘贴,一验证,哎,咱这代码正常运行,符合预期,就完事儿啦。尽量看的远一点。


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!