spring boot 程式啟動緩慢的問題
https://blog.csdn.net/yt4766269/article/details/78439811
今天發現一臺伺服器上的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以上的版本,在啟動時會呼叫SecureRandom
類來生成隨機數。如果用於初始化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
就會造成阻塞,直到收集到了足夠的熵,程式才會繼續往下進行。
(關於什麼是/dev/random
,可以檢視 wiki的介紹)
解決方法是修改成非阻塞的熵源/dev/urandom
。
可以修改java.security
檔案中的securerandom.source
值,也可以使用引數java.security.egd
:
java -jar app.jar -Djava.security.egd=file:/dev/./urandom
至於為什麼是/dev/./urandom
,而不是/dev/urandom
,這源於java的一個bug。大意是/dev/urandom
在某些情況下可能還是最終會轉換成呼叫/dev/random
。所以為了保險起見,還是使用/dev/./urandom
吧!