先在指定目录创建一个shell脚本
第一种方法,缺点是,这个restart.sh停了,就不会监测了
编辑
#这是针对于一个jar包的自启
#!/bin/bash
source /etc/profile
while true
do
ps -ef | grep "自己的jar包" | grep -v "grep"
if [ "$?" -eq 1 ];then
nohup java -jar 自己的jar包 >catalina.out 2>&1 &
fi
sleep 60
done
#这是针对于多个jar包的自启
#!/bin/bash
source /etc/profile
# 定义一个关联数组,包含所有的 JAR 包名称和对应的密钥
declare -A jar_packages=(
["student.jar"]="--mpw.key=1fcb6c790f19f9ex"
["rebuild.jar"]=""
)
while true
do
for package in "${!jar_packages[@]}"
do
ps -ef | grep "$package" | grep -v "grep"
if [ "$?" -eq 1 ]; then
nohup java -jar "$package" "${jar_packages[$package]}" > "$package.out" &
fi
done
sleep 60
done
给脚本授权
将shell脚本在后台运行起来
nohup ./restart.sh > restart.log &
第二种方法
#!/bin/bash
# JAR包和日志文件存放位置--根据自己的情况修改
dir=/root
# 定义一个数组,包含需要监控的JAR包和对应的密钥
declare -A processes=(
["student.jar"]="--mpw.key=1fcb6c790f19f9ex"
["rebuild.jar"]=""
)
# 遍历JAR包数组
for process in "${!processes[@]}"
do
# 查看JAR包运行进程的PID
pid=$(ps -ef | grep "$dir/$process" | grep 'java' | grep -v grep | awk '{print $2}')
# 如果进程不存在,重启JAR包服务
if [ -z "$pid" ]; then
# 从关联数组中获取对应的密钥
key="${processes[$process]}"
if [ -n "$key" ]; then
# 使用密钥启动JAR包
source /etc/profile
nohup java -jar "$dir/$process" "$key" >> "$dir/$process.out" &
else
# 不使用密钥启动JAR包
source /etc/profile
nohup java -jar "$dir/$process" >> "$dir/$process.out" &
fi
echo $(date +"%Y-%m-%d %T") "__程序 $process 宕机,自动重启" >> "$dir/info.log"
fi
done
写入定时任务
crontab -e
#在定时任务中设定任务,5分钟检查一次
*/5 * * * * sh /xxx/xxx/restart.sh