在实际项目应用中,为了避免有可能因为系统重启或异常,导致服务进程终止的情况,需要对服务加入自启动和监视进程。
即系统重启时启动相关服务,服务异常时重启服务并发送提醒邮件至管理员邮箱。系统以centos为例:
1、修改系统初始化脚本
打开/etc/rc.d/rc.local脚本,该脚本为系统初始化完成时调用,添加相关启动命令即可,例如:
#!/bin/sh # # This script will be executed *after* all the other init scripts. # You can put your own initialization stuff in here if you don't # want to do the full Sys V style init stuff. touch /var/lock/subsys/local ...
2、部署服务守护进程
编写监视服务运行的执行文件monitor,例如:
#!/bin/bash #文件说明:监控应用程序运行,如已退出则启动应用程序 export LANG=zh_CN.UTF-8 IP=`/sbin/ifconfig eth0 | grep "inet addr" | cut -f 2 -d ":" | cut -f 1 -d " "` monitor_path=/wwwroot/monitor declare -a Emaillist Emaillist[0]=XXX@163.com #服务名列表 declare -a app_name_list #服务路径列表 declare -a app_path_list #服务1: app_name_list[0]=XXX1 app_path_list[0]=/wwwroot/XXX1/ #服务2: app_name_list[1]=XXX2 app_path_list[1]=/wwwroot/XXX2/ i=0 for app_name in ${app_name_list[*]} do Count=`ps -ef | grep $app_name | wc -l` if [[ $Count -eq 1 ]]; then ${app_path_list[i]}/$app_name & for email in ${Emaillist[*]} do echo "服务器[$IP]: [$app_name]程序运行终止,现已启动该应用,请检查终止原因!" | mutt -s "服务器[$IP][$app_name]运行告警" $email done echo "$(date "+%Y-%m-%d %H:%M:%S") [$app_name]服务器程序运行终止,现已启动该应用,请检查终止原因!" >> $monitor_path/monitor.log fi let i++ done
3、将monitor添加到任务计划
Crontab任务计划是系统自带的,如果没安装请自行安装。
在/etc/cron.d目录下新建一个叫webervice的文件,按照任务计划命令格式添加:
*/1 * * * * /wwwroot/monitor/monitor
*/1代每秒钟执行一次
浙公网安备 33010602011771号