比如有三个服务,
为了减少故障时间,增加监控任务,使用linux的 crontab 实现.
步骤:
1,每个服务写一个ping接口
监控如下内容:
1,HouseServer 是否正常运行,所以需要增加一个ping的接口 ; http://house.yhskyc.com/ping 2,gitlab服务是否正常访问 http://git.yhskyc.com/users/sign_in 返回HTML 包含"Open source software to collaborate on code"; 3,小幺鸡,是否正常 http://api.yunmasoft.com/api/ping/xiaoyaoji标准:不要求接口正确性,只要求返回200就行
2,封装一个可执行的jar包专门用来发送短信
执行如下命令,即可发送短信
/usr/java/jdk1.8.0_152/bin/java -jar sendsmsbyqcloud-0.0.1-snapshot.jar 18732670186 "服务器挂了,请速检查`date +%F`"
短信发送使用腾讯云
参考:
https://console.cloud.tencent.com/sms/smsinfo/1400091325/0
认证信息: https://console.cloud.tencent.com/developer/auth发送短信的可执行jar包
java -jar sendSMSByQcloud-0.0.1-SNAPSHOT.jar 18743210186 请去检查服务器 log4j:WARN No appenders could be found for logger (com.io.hw.json.HWJacksonUtils). log4j:WARN Please initialize the log4j system properly. :{"appid":1400091325,"appkey":"ab14f5b7a06feab6b8f91af82ce75663","mobile":"18701670186","msg":"请去检查服务器"} {"result":0,"errmsg":"OK","ext":"","sid":"8:cV1DTDeJxq1qqSnbwvs20180625","fee":1}
3,写linux shell脚本,用于判断接口是否正常
脚本名称:monitor2.sh
#!/bin/bash# monitor if Service normal,send SMS when ether service is downsendSMS(){echo "error.发送短信"cd /home/whuang/bin/sms/usr/java/jdk1.8.0_152/bin/java -jar sendsmsbyqcloud-0.0.1-snapshot.jar 18743670186 "服务器挂了,请速检查`date +%F`"}testHttp(){url2="$1"xiaoyaoji_result=`curl --get --compressed $url2` >>/dev/null#echo "resut111:$xiaoyaoji_result"echo "$xiaoyaoji_result" |grep "true"result2=$?#echo $result2if [ $result2 -ne 0 ];then sendSMS exit 14fi}testHttpGitLab(){xiaoyaoji_result=`curl --get --compressed 'http://git.yhskyc.com/users/sign_in'` >>/dev/null#echo "resut111:$xiaoyaoji_result"echo "$xiaoyaoji_result" |grep "Open source software to collaborate on code"result2=$?#echo $result2if [ $result2 -ne 0 ];then sendSMS exit 14fi}testHttp 'http://house.yhskyc.com/ping'testHttp 'http://api.yunmasoft.com/api/ping/xiaoyaoji'testHttpGitLab
脚本说明:
1, sendSMS,testHttp 是shell 函数;
2,使用grep来校验接口返回结果.
3,发送短信命令:
/usr/java/jdk1.8.0_152/bin/java -jar sendsmsbyqcloud-0.0.1-snapshot.jar 18732170186 "服务器挂了,请速检查`date +%F`"
蓝色标记的是jar包的参数
注意:
可能crontab 中执行时会出现如下两个错误:
(1)找不到java命令,
解决 方法:java命令使用绝对路径
(2)shell脚本中使用相对路径的统一改为绝对路径
4,创建定时任务
*/10 * * * * /home/whuang/bin/sms/monitor2.sh 2>> /home/whuang/bin/sms/error.log
命令:crontab -e
linux crontab 语法说明:
*/20 * * * * /Users/whuanghk/study/cron/todo.sh
每20分钟执行一次 20 7 * * * /home/whuang/software/auto_start_tomcat.sh 每天的上午7点20分执行脚本