区分JDK版本是16还是非16
jdk16查看内存工具
jhsdb jmap --heap --pid pid
非16版本查看内存工具
jmap -heap pid
脚本文件名:/mnt/disk/app/monitor/jvm_monitor.sh
监控脚本内容
#!/bin/bash
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/home/rocketmq/bin:/usr/local/jdk16/bin:/usr/local/git/bin:/usr/local/node/bin:/root/bin
#jdk版本号
jdkVersion=`java -version 2>&1 | sed '1!d' | sed -e 's/"//g' | awk '{print $3}'`
sysdate=`date +"%Y-%m-%d %H:%M:%S" -d now`
for pid in `jps |grep -v Jps|awk '{print $1}'`
do
process_name=$(ps -ef|grep java|grep $pid)
#jvm内存监控
echo -------------------------------------------------
echo 日期:$sysdate
echo JDK版本:$jdkVersion
echo 进程ID:${pid}
echo 进程信息:${process_name}
if [ "$pid" = "" ]
then
echo "the program is not exists."
exit 0
fi
if [[ ${jdkVersion} == 16 ]]
then
heap=$(jhsdb jmap --heap --pid ${pid})
else
heap=$(jmap -heap ${pid})
fi
G1Heap=`echo ${heap}|sed 's/^.*G1 Heap://g'|sed 's/G1 Young Generation:.*$//g'|awk '{print $16}'|sed 's/%.*$//g'|cut -b 1-6`
G1Old=`echo ${heap}|sed 's/^.*G1 Old Generation://g'|awk '{print $16}'|sed 's/%.*$//g'|cut -b 1-6`
echo "当前JVM堆区使用率: ${G1Heap}%"
echo "当前JVM老年代堆区使用率: ${G1Old}%"
G1Heap1=`gawk -v x=$G1Heap -v y=1000 'BEGIN{printf "%.0f\n",x*y}'`
G1Old1=`gawk -v x=$G1Old -v y=1000 'BEGIN{printf "%.0f\n",x*y}'`
#解析IP地址
interIp=$(ip addr | awk '/^[0-9]+: / {}; /inet.*global/ {print gensub(/(.*)\/(.*)/, "\\1", "g", $2)}')
sendMsg=""
if [ ${G1Heap1} -ge "85000" ]
then
sendMsg=${sendMsg}" dev":${interIp}" "PID:${pid}" "JVM堆区使用率:${G1Heap}%超阀值"\n"
fi
if [ ${G1Old1} -ge "85000" ]
then
sendMsg=${sendMsg}" dev"IP:${interIp}" "PID:${pid}" "JVM老年代堆区使用率:${G1Old}%超阀值
fi
if [ -n "${sendMsg}" ]; then
sendMsg=${sysdate}" "${sendMsg}
echo "发送消息:"$sendMsg
curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=7c07644b-91eb-498c-9a78-045575cc67b8' -H 'Content-Type: application/json' -d "{\"msgtype\": \"text\",\"text\": {\"content\": \"${sendMsg}\",\"mentioned_mobile_list\":[]}}"
fi
done
chmod +x /mnt/disk/app/monitor/jvm_monitor.sh
添加系统任务,每隔3分钟执行一次监控脚本
crontab -e
*/3 * * * * /mnt/disk/app/monitor/jvm_monitor.sh >> /mnt/disk/app/monitor/jvm_monitor.log 2>&1
重新载入配置
service crond reload