一、背景
jvm进程经常会自己挂掉,原因有很多,比如断电,被误杀等。所以我们需要有一套脚本,定期检测jvm端口是否存在,如果不存在,则需要自动重启。
二、依赖的组件
1、crontab -e
# 每分钟监听jvm进程
*/1 * * * * /bin/sh /opt/monitor.sh
2、monitor.sh
#! /bin/sh
source /etc/profile
cd /server/cwp-to-video/
# 进程1
procnum=`ps -ef|grep cwp2video|grep -v grep|wc -l`
if [ $procnum -eq 0 ]
then
echo `date +%Y-%m-%d` `date +%H:%M:%S` "restart service cwp2video" >>/opt/restart-cwp2video.log
sh ./cwp2video-evolution/bin/startup.sh restart
fi
# 进程2
adbProcnum=`ps -ef|grep adb-screen|grep -v grep|wc -l`
if [ $adbProcnum -eq 0 ]
then
echo `date +%Y-%m-%d` `date +%H:%M:%S` "restart service adb-screen" >>/opt/restart-adb-screen.log
sh ./adb-screen-service/bin/startup.sh restart
fi
3、startup.sh
各自实现不同,这里仅列出我们的实现,以作参考
- 启动的时候,保存好进程号,在停止或重启的时候,只需要读取文件里的进程号,然后kill {pid}
source /etc/profile
service=adb-screen-service
basepath=/server/cwp-to-video/${service}
start() {
nohup java -Dfile.encoding="UTF-8" -Duser.timezone=Asia/Shanghai -Dserver.ip=192.168.53.29 -Dspring.config.location=${basepath}/bin/application.yml -Xms64m -Xmx512m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${basepath}/dump/ -jar ${basepath}/packages/${service}.jar >> ${basepath}/logs/${service}.log 2>&1 &
echo $! > ${basepath}/pid
}
stop() {
kill -9 `cat $basepath/pid`
rm -rf $basepath/pid
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
sleep 1
start
;;
health)
$basepath/bin/health.sh
;;
*)
echo "Usage: run.sh {start|stop|restart}"
;;
esac
exit 0
三、补充部分
image.png[root@localhost opt]# jps
16496 adb-screen-service.jar
20168 Jps
2506 cwp2video-evolution.jar
3.1、查找jvm进程ID
echo `ps -ef|grep 'adb-screen-service'|grep -v grep|awk '{print $2}'`
3.2、杀掉jvm进程
kill -9 `ps -ef|grep 'adb-screen-service'|grep -v grep|awk '{print $2}'`
3.3、把进程ID存入到文件里
echo $! > ${basepath}/pid
kill -9 `cat $basepath/pid`
四、验证
image.png杀掉进程,等待一分钟左右,可以看到会有自动重启jvm服务的日志输出。
> cat restart-adb-screen.log
2022-08-09 10:18:02 restart service adb-screen
网友评论