shutdown.sh -force保證tomcat完全關(guān)閉
直接使用shutdown.sh不能完全關(guān)閉tomcat的情況,多見在tomcat中使用了線程池,并且線程不都是守護(hù)線程。一般我們手動ps找到tomcat的pid并kill,但其實tomcat自帶的腳本已經(jīng)有了這個功能。
- tomcat的catalina.sh中說明了如果想要加什么參數(shù),不要修改catalina.sh,在
CATALINA_BASE/bin創(chuàng)建一個setenv.sh,并設(shè)置CATALINA_OPTS。 -
JAVA_OPTS中的參數(shù)在關(guān)閉tomcat的時候也會參與,大部分的參數(shù)應(yīng)該放到CATALINA_OPTS中。CATALINA_OPTS只在tomcat啟動中參與。 -
CATALINA_PID中會存放tomcat啟動后的pid。 - 使用shutdown.sh的時候添加-force參數(shù),如果5s后tomcat還存活會使用kill命令殺掉,還可以通過-n制定等待秒數(shù),kill的進(jìn)程號需要
CATALINA_PID參數(shù) - catalina.sh中和本文有關(guān)的內(nèi)容如下
# Do not set the variables in this script. Instead put them into a script
# setenv.sh in CATALINA_BASE/bin to keep your customizations separate.
# CATALINA_OPTS (Optional) Java runtime options used when the "start",
# "run" or "debug" command is executed.
# JAVA_OPTS (Optional) Java runtime options used when any command
# is executed.
# Most options should go into CATALINA_OPTS.
# CATALINA_PID (Optional) Path of the file which should contains the pid
# of the catalina startup java process, when start (fork) is
# used
echo " stop -force Stop Catalina, wait up to 5 seconds and then use kill -KILL if still running"
echo " stop n -force Stop Catalina, wait up to n seconds and then use kill -KILL if still running"
echo "Note: Waiting for the process to end and use of the -force option require that \$CATALINA_PID is defined"
- 創(chuàng)建如下內(nèi)容的setenv.sh
加入了遠(yuǎn)程調(diào)試功能(參數(shù)含義可以看我之前的文章),并且指定了隨機(jī)數(shù)生成器(后面解釋這個)。
tomcat啟動時會在$CATALINA_HOME/bin下新生成tomcat.pid文件存放pid,并把pid的值賦給CATALINA_PID參數(shù)
#!/bin/sh
CATALINA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=127.0.0.1:9000 -Djava.security.egd=file:/dev/urandom"
CATALINA_PID=$CATALINA_HOME/bin/tomcat.pid
解決tomcat啟動超慢的問題
centos7 遇到了這個問題,每次啟動tomcat的catalina.out日志中has finished in [xxx] ms。這個xxx每次都不一樣,幾十秒到幾百秒都有可能。在StackOverflow中找到了原因
- tomcat啟動慢的罪魁禍?zhǔn)资菃訒r實例化一個SecureRandom實例特別慢,catalina.out中日志如下:
Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took **[1,718,769] milliseconds.**
- 構(gòu)造SecureRandom實例會使用系統(tǒng)的/dev/random生成隨機(jī)數(shù),但是/dev/random依賴系統(tǒng)中斷,所以隨機(jī)數(shù)更加隨機(jī)但是產(chǎn)生的可能會很慢
- 所以我們使用/dev/urandom代替/dev/random就可以了,這兩個隨機(jī)數(shù)生成器的區(qū)別網(wǎng)上一堆,這里不貼了
- 有兩種解決辦法
- 在tomcat啟動參數(shù)中指定Djava.security.egd=file:/dev/urandom(和上面)
- 修改
/usr/java/default/jre/lib/security/java.security中指定securerandom.source=file:/dev/urandom
PS:我現(xiàn)在使用的是第二種方法,因為我發(fā)現(xiàn)公司的運(yùn)維交付給我們使用的虛擬機(jī)都是這樣做的