linux下监控java进程 实现自动重启服务

实现对进程的监控这里只需要三步:

  1. 设置服务启动脚本
  2. 设置监控shell脚本
  3. 设置linux周期定时执行指令

设置服务启动脚本
vi app.sh
脚本内容如下

#!/bin/bash
#这里可替换为你自己的执行程序,其他代码无需更改
APP_NAME=app.jar

#使用说明,用来提示输入参数
usage() {
    echo "Usage: sh 脚本名.sh [start|stop|restart|status]"
    exit 1
}

#检查程序是否在运行
is_exist(){
  pid=`ps -ef|grep $APP_NAME|grep -v grep|awk '{print $2}' `
  #如果不存在返回1,存在返回0
  if [ -z "${pid}" ]; then
   return 1
  else
    return 0
  fi
}

#启动方法
start(){
  is_exist
  if [ $? -eq "0" ]; then
    echo "${APP_NAME} is already running. pid=${pid} ."
  else
    #启动时设置并发垃圾收集器
        nohup java -XX:+UseConcMarkSweepGC -XX:+UseCMSCompactAtFullCollection -XX:CMSFullGCsBeforeCompaction=5 -jar taskcenter.jar > taskcenterlog.file 2>&1 &
    echo "${APP_NAME} start success"
  fi
}

#停止方法
stop(){
  is_exist
  if [ $? -eq "0" ]; then
    kill -9 $pid
  else
    echo "${APP_NAME} is not running"
  fi
}

#输出运行状态
status(){
  is_exist
  if [ $? -eq "0" ]; then
    echo "${APP_NAME} is running. Pid is ${pid}"
  else
    echo "${APP_NAME} is NOT running."
  fi
}

#重启
restart(){
  stop
  start
}

#根据输入参数,选择执行对应方法,不输入则执行使用说明
case "$1" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  "restart")
    restart
    ;;
  *)
    usage
    ;;
esac

添加脚本权限
chmod +x app.sh

注:脚本需要和jar包在同一级目录下

设置监控shell脚本
vi monitor.sh
脚本内容如下

#! /bin/sh

source /etc/profile

#这里是你监控脚本的目录
cd /data/taskcenter

procnum=`ps -ef|grep app.jar|grep -v grep|wc -l`
if [ $procnum -eq 0 ]
then
    echo `date +%Y-%m-%d` `date +%H:%M:%S` "restart service" >>/root/logs/restart.log
    #这个是你启动脚本的目录 如果跟监控脚本在同一目录 就是./app.sh 后面是启动命令
    ./app.sh start
fi

添加脚本权限
chmod +x monitor.sh

设置linux周期定时执行指令 将monitor.sh脚本加入crontab

输入命令: crontab -e

然后打开的文件中输入以下脚本内容


#开机自启动任务
@reboot /bin/sh /data/taskcenter/monitor.sh

#每分钟执行一次监控脚本
* * * * * /bin/sh /data/taskcenter/monitor.sh

然后:wq保存
控制台输出“crontab: installing new crontab”,表示任务添加成功

文章持续更新,可以关注下方公众号或者微信搜一搜「 最后一支迷迭香 」第一时间阅读,获取更完整的链路资料。

  • 4
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

最后一支迷迭香

您的赞赏将给作者加杯☕️

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值