# auto-monitor-java-process
**Repository Path**: jialy/auto-monitor-java-process
## Basic Information
- **Project Name**: auto-monitor-java-process
- **Description**: 自动监控java进程cpu使用率及进程中线程cpu占用情况
- **Primary Language**: Shell
- **License**: MIT
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 5
- **Forks**: 1
- **Created**: 2021-01-08
- **Last Updated**: 2025-04-09
## Categories & Tags
**Categories**: Uncategorized
**Tags**: shell, CPU
## README
### 通过Shell脚本自动监控JAVA进程中线程cpu使用率
本文主要介绍在 show-busy-java-threads.sh 脚本的功能基础上,通过 [process-cpu-monitor.sh]() 脚本实现`Linux`平台上`Java`进程或服务的线程繁忙情况监控。
`show-busy-java-threads.sh`是一个能够打印`Java`进程中线程`cpu`使用率的脚本,可以用来排查程序`cpu`使用率异常的情况。详细使用方法--\>传送门
尽管`show-busy-java-threads.sh`功能很强大,但是它不支持`cpu`使用率监控功能。一般都是`cpu`开始报警之后才人为去触发,就显得为时已晚,往往就错过了最想要的数据。
而`process-cpu-monitor.sh`脚本就实现了对进程`cpu`使用率的监控,当监控到进程`cpu`使用率超过设定的值时,就执行`show-busy-java-threads.sh`脚本来实时抓取进程中线程`cpu`的使用情况。
#### 使用说明
脚本可接收两个参数,首个参数表示要监控的进程(必传),值可以为`进程pid值`、`pid文件`或者`服务名`。第二个参数是监控的`cpu使用率`(可选),0~100数值,表示超过设定的值就执行`show-busy-java-threads.sh`脚本,默认为95。
脚本中的`busyThreadLog`和`busyThreadPid`定义了执行`show-busy-java-threads.sh`脚本进程的pid和线程监控情况的输出,使用前请自行修改。同时其执行参数默认如下:
```bash
nohup sh show-busy-java-threads.sh 5 60 -c 20 -p $pid
```
#### process-cpu-monitor.sh用法
```bash
process-cpu-monitor.sh 32145
# 监控进程PID为32145的java服务
process-cpu-monitor.sh /temp/xxxpid
# /temp/xxxpid 表示进程pid文件,文件内容进程pid值
process-cpu-monitor.sh mall-service
# mall-service Java服务名,可能是main类名的一部分或执行jar或war名包的一部分
process-cpu-monitor.sh 32145 80
# 监控进程PID为32145的java服务,当进程cpu使用超过80%时,开始执行监控线程的脚本
nohup ./process-cpu-monitor.sh mall-service >/dev/null 2>&1 &
# 以守护进程的方式执行脚本,/dev/null可以替换想要输出的文件
```
#### 开机自启动
1. 通过修改/etc/rc.d/rc.local文件来实现启动执行监控脚本
2. 在使用systemd的系统上,创建一个systemd的启动服务来执行脚本
3. 使用crontab来开机启动执行脚本