监控谷歌浏览器CPU及内存使用情况

该项目是一个使用JAVA开发的应用,被打包成exe可执行程序,具备监控指定进程(如Chrome)的CPU和内存使用情况的功能。当超过预设阀值时,程序会通过企业微信群机器人或飞书群机器人发送告警消息。配置包括POM文件设置依赖,以及FX界面用于用户输入阀值和告警地址。
摘要由CSDN通过智能技术生成

项目使用JAVA开发打包成exe执行程序,支持推送企业微信群机器人和飞书群机器人

1,POM文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lingxiao</groupId>
    <artifactId>lingxiao-monitor</artifactId>
    <version>1.0</version>

    <dependencies>
        <dependency>
            <groupId>com.github.oshi</groupId>
            <artifactId>oshi-core</artifactId>
            <version>6.4.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>2.0.23</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>com.zenjava</groupId>
                <artifactId>javafx-maven-plugin</artifactId>
                <version>8.8.3</version>
                <configuration>
                    <vendor>lingxiao</vendor>
                    <mainClass>com.lingxiao.Mm</mainClass>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

2,代码文件

package com.lingxiao;
import com.alibaba.fastjson2.JSONObject;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
import oshi.software.os.OSProcess;
import oshi.software.os.OperatingSystem;
import oshi.software.os.windows.WindowsOperatingSystem;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;


public class Mm extends Application {
    private String mess;
    private BigDecimal cpu;
    private BigDecimal mem;
    private final static  String MARK = "chrome";

    public static void main(String[] args) {
        launch();
    }

    public void start(Stage primaryStage)  {
        FlowPane pane = new FlowPane();
        pane.setPadding(new Insets(11,500,13,14));
        pane.setHgap(5);
        pane.setVgap(5);

        Label lab1 = new Label("CPU阀值(格式:3.00)");
        Label lab2 = new Label("内存阀值/M(格式:500)");
        Label lab3 = new Label("标识名称(格式:环保大屏1号)");
        Label lab4 = new Label("告警推送地址(格式:webhook)");

        TextField text1 = new TextField();
        TextField text2 = new TextField();
        TextField text3 = new TextField();
        TextField text4 = new TextField();
        text4.setPrefWidth(320);
        TextArea result = new TextArea();
        result.setPrefWidth(320);
        result.setPrefHeight(160);

        Button button = new Button("启动");

        button.setOnAction(e-> {
                String value1 = text1.getText();
                String value2 = text2.getText();
                String value3 = text3.getText();
                String value4 = text4.getText();
            Alert alert = new Alert(Alert.AlertType.WARNING);
            if(value1 == null || value1.trim().isEmpty()){
                alert.setContentText("CPU阀值设置有误");
                alert.showAndWait();
                return;
            }
            if(value2 == null || value2.trim().isEmpty()){
                alert.setContentText("内存阀值设置有误");
                alert.showAndWait();
                return;
            }
            if(value3 == null || value3.trim().isEmpty()){
                alert.setContentText("标识名称设置有误");
                alert.showAndWait();
                return;
            }
            if(value4 == null || value4.trim().isEmpty()){
                alert.setContentText("告警推送地址设置有误");
                alert.showAndWait();
                return;
            }
            // 创建任务队列
            ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
            //执行任务
            scheduledExecutorService.scheduleAtFixedRate(() -> {
                if(monitor(value1,value2)){
                    webhook(value3,value4);
                }
                result.setText(this.mess);
            },0,1, TimeUnit.MINUTES);
            text1.setDisable(true);
            text2.setDisable(true);
            text3.setDisable(true);
            text4.setDisable(true);
            button.setDisable(true);
        });
        pane.getChildren().addAll(lab1,text1,lab2,text2,lab3,text3,lab4,text4,button,result);
        Scene scene = new Scene(pane, 360, 400);
        primaryStage.setTitle("lingxiao-monitor");
        primaryStage.setScene(scene);
        primaryStage.sizeToScene();
        primaryStage.show();
    }

    /**
     * 判断CPU或者内存是否超过阀值
     * @param v1 CPU阀值
     * @param v2 内存阀值
     * @return
     */
    private boolean monitor(String v1,String v2){
        this.mess = "";
        this.cpu = new BigDecimal(0) ;
        this.mem = new BigDecimal(0);
        BigDecimal value1 = new BigDecimal(v1);
        BigDecimal value2 = new BigDecimal(v2);

        OperatingSystem windowsOperatingSystem = new WindowsOperatingSystem();
        Predicate<OSProcess> predicate = new Predicate<OSProcess>() {
            @Override
            public boolean test(OSProcess t) {
                return t.getName().equals(MARK);
            }
        };
        List<OSProcess> processList = windowsOperatingSystem.getProcesses(predicate,null,0);
        for (OSProcess process:processList) {
            this.mess = this.mess  + String.format("名称:%s PID: %d CPU:%.2f 内存:%dM",
                    process.getName(),
                    process.getProcessID(),
                    process.getProcessCpuLoadCumulative(),
                    process.getResidentSetSize()/1024/1024)+"\n";
            this.cpu = this.cpu.add(new BigDecimal(process.getProcessCpuLoadCumulative()).setScale(2, RoundingMode.HALF_UP));
            this.mem = this.mem.add(new BigDecimal (process.getResidentSetSize()/1024/1024));

        }
        this.mess = "cpu合计:"+this.cpu +"    内存合计:"+this.mem +"M"
                +"\n========================="
                +"\n"+this.mess;
        return this.cpu.compareTo(value1) == 1 || this.mem.compareTo(value2) == 1;
    }

    /**
     * 发送webhook消息
     * @param v3 标识名称
     * @param v4 告警推送地址
     */
    private void webhook(String v3 ,String v4){
        HttpURLConnection conn = null;
        try {
            URL url = new URL(v4);
            conn = (HttpURLConnection) url.openConnection();
            // 设置请求的属性
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(60000);
            conn.setReadTimeout(60000);
            conn.setConnectTimeout(60000);
            conn.setRequestProperty("Content-type", "application/json");
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            String text = v3+"  CPU使用:"+this.cpu+"  内存使用:"+this.mem+"M  已超阀值,请抓紧处理!";
            JSONObject params = new JSONObject();
            if(v4.indexOf("weixin") > 0){
                params.put("msgtype", "text");
            }else{
                params.put("msg_type", "text");
            }
            JSONObject content = new JSONObject();
            content.put("text", text);
            params.put("content", content);
            os.write(params.toString().getBytes("UTF-8"));
            os.flush();
            os.close();
            conn.getResponseCode();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

3,打包后程序

在这里插入图片描述

4,告警效果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值