springboot的tomcat啟動過慢的問題分析

今天發(fā)現(xiàn)一臺服務器上的springboot程序啟動特別慢,完全啟動起來用了有好幾分鐘。剛開始以為是代碼寫的有問題造成了卡死,直到看到這條log:

2017-03-08 10:06:49.600  INFO 6439 --- [main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8888 (http)
2017-03-08 10:06:49.613  INFO 6439 --- [main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2017-03-08 10:06:49.614  INFO 6439 --- [main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.37
......
2017-03-08 10:09:10.167  INFO 6439 --- [ost-startStop-1] o.a.c.util.SessionIdGeneratorBase        : Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [140,108] milliseconds.

原來是tomcat的啟動耗費了140多秒。而罪魁禍首是這個SecureRandom類。

其實,這個問題我之前就有耳聞,但從沒遇到過,也就沒太在意。今天終于讓我遇上了,墨菲定律又生生應驗了一回。。


tomcat的文檔里有個概念叫Entropy Source(熵源)

Tomcat 7+ heavily relies on SecureRandom class to provide random values for its session ids and in other places. Depending on your JRE it can cause delays during startup if entropy source that is used to initialize SecureRandom is short of entropy. You will see warning in the logs when this happens, e.g.:
<DATE> org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [5172] milliseconds.

意思是tomcat7以上的版本,在啟動時會調(diào)用SecureRandom類來生成隨機數(shù)。如果用于初始化SecureRandom熵源是個短熵(熵不夠用),那么就會報文章開頭說的warning了。


jdk的配置文件中,使用securerandom.source設置了熵源:

cat /usr/java/jdk1.8.0_121/jre/lib/security/java.security

securerandom.source=file:/dev/random

可以看到默認值是:/dev/random
所以程序啟動后SecureRandom類會讀取/dev/random以獲取隨機序列,這是一個同步操作。當熵池(entropy pool) 中沒有足夠的熵時,讀取/dev/random就會造成阻塞,直到收集到了足夠的熵,程序才會繼續(xù)往下進行。
(關于什么是/dev/random,可以查看 wiki的介紹


解決方法是修改成非阻塞的熵源/dev/urandom。
可以修改java.security文件中的securerandom.source值,也可以使用參數(shù)java.security.egd

java -jar app.jar -Djava.security.egd=file:/dev/./urandom

至于為什么是/dev/./urandom,而不是/dev/urandom,這源于java的一個bug。大意是/dev/urandom在某些情況下可能還是最終會轉(zhuǎn)換成調(diào)用/dev/random。所以為了保險起見,還是使用/dev/./urandom吧!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容