系统资源监控相关代码

本文获取计算机信息;包含cpu、gpu、内存、磁盘、系统、jvm、网络情况。

1.依赖包
        <dependency>
            <groupId>com.github.oshi</groupId>
            <artifactId>oshi-core</artifactId>
            <version>5.8.1</version>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.0</version>
        </dependency>
2.工具类
package com.mxpt.resource.manage.utils;

import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.system.oshi.OshiUtil;
import com.mxpt.common.core.utils.StringUtils;
import com.mxpt.resource.manage.model.ComputerInfo;
import com.mxpt.resource.manage.model.CpuInfo;
import com.mxpt.resource.manage.model.GPUInfo;
import com.mxpt.resource.manage.model.JvmInfo;
import com.mxpt.resource.manage.model.MemInfo;
import com.mxpt.resource.manage.model.NetInfo;
import com.mxpt.resource.manage.model.SysFile;
import com.mxpt.resource.manage.model.SysInfo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import oshi.SystemInfo;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.hardware.NetworkIF;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 *
  * @author lfh
  * @description 获取系统信息工具类
  * @date 2024/3/23 16:20
 */
@Data
@Slf4j
public class SystemUtils implements Serializable {

    private static final long serialVersionUID = 1L;
    private static SystemUtils systemUtils;

    public static void main(String[] args) {
        SystemUtils instance = getInstance();
        ComputerInfo computerInfo = instance.computerInfo();
        log.info(computerInfo.toString());
    }

    /**
     * 私有构造
     */
    private SystemUtils() {
    }


    /**
     * 单例获取
     *
     * @return 对象
     */
    public static SystemUtils getInstance() {
        if (StringUtils.isNull(systemUtils)) {
            synchronized (SystemUtils.class) {
                if (StringUtils.isNull(systemUtils)) {
                    systemUtils = new SystemUtils();
                }
            }
        }
        return systemUtils;
    }

    public ComputerInfo computerInfo() {
        ComputerInfo computerInfo = new ComputerInfo();
        CpuInfo cpuInfo = cpuInfo();
        computerInfo.setCpuInfo(cpuInfo);
        List<GPUInfo> gpuInfos = gpuInfo();
        computerInfo.setGpuInfos(gpuInfos);
        NetInfo net = net();
        computerInfo.setNetInfo(net);
        MemInfo memInfo = memInfo();
        computerInfo.setMemInfo(memInfo);
        SysInfo sysInfo = sysInfo();
        computerInfo.setSysInfo(sysInfo);
        JvmInfo jvmInfo = jvmInfo();
        computerInfo.setJvmInfo(jvmInfo);
        List<SysFile> sysFiles = sysFiles();
        computerInfo.setSysFiles(sysFiles);
        return computerInfo;
    }

    public List<GPUInfo> gpuInfo() {
        List<GPUInfo> gpuInfos = new ArrayList<>();
        try {
            ProcessBuilder pb = new ProcessBuilder("nvidia-smi", "--query-gpu=index,name,temperature.gpu,utilization.gpu,memory.total,memory.free", "--format=csv,noheader");
            Process p = pb.start();

            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length == 6) {
                    int gpuId = Integer.parseInt(parts[0]);
                    String name = parts[1];
                    int temperature = Integer.parseInt(parts[2].trim().split(" ")[0]);
                    int utilization = Integer.parseInt(parts[3].trim().split(" ")[0]);
                    int memoryTotal = Integer.parseInt(parts[4].trim().split(" ")[0]);
                    int memoryFree = Integer.parseInt(parts[5].trim().split(" ")[0]);

                    GPUInfo gpuInfo = new GPUInfo(gpuId, name, temperature, utilization, memoryTotal, memoryFree);
                    gpuInfos.add(gpuInfo);
                }
            }

            reader.close();
            p.waitFor();
        } catch (IOException | InterruptedException e) {
            log.error("【gpuInfo】 获取GPU信息失败", e);
            Thread.currentThread().interrupt();
        }
        return gpuInfos;
    }

    /**
     * 获取网络信息
     *
     * @return 网络模型
     */
    public NetInfo net() {
        HardwareAbstractionLayer hardware = OshiUtil.getHardware();
        List<NetworkIF> networkIFs = hardware.getNetworkIFs();
        long up = 0;
        long down = 0;
        long time = 0;
        for (NetworkIF net : networkIFs) {
            long bytesRecv = net.getBytesRecv();
            long bytesSent = net.getBytesSent();
            long timeStamp = net.getTimeStamp();
            up += bytesSent;
            down += bytesRecv;
            time += timeStamp;
        }
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            log.error("【net】 获取网络信息失败", e);
            Thread.currentThread().interrupt();
        }

        networkIFs = hardware.getNetworkIFs();
        long upload = 0L;
        long download = 0L;
        long timeT = 0L;
        for (NetworkIF net : networkIFs) {
            long bytesSent = net.getBytesSent();
            long bytesRecv = net.getBytesRecv();
            long timeStamp = net.getTimeStamp();
            timeT += timeStamp;
            upload += bytesSent;
            download += bytesRecv;
        }
        NetInfo netInfo = new NetInfo();
        if (timeT != time) {
            String downloadStr = formatData((download - down) / (timeT - time) * 1000) + "/s";
            String uploadStr = formatData((upload - up) / (timeT - time) * 1000) + "/s";
            netInfo.setDown(downloadStr);
            netInfo.setUp(uploadStr);
        }
        return netInfo;
    }

    /**
     * 设置CPU信息
     */
    public CpuInfo cpuInfo() {
        cn.hutool.system.oshi.CpuInfo cpuInfo = OshiUtil.getCpuInfo();
        CpuInfo cpu = new CpuInfo();
        cpu.setCpuNum(cpuInfo.getCpuNum());
        cpu.setSys(cpuInfo.getSys());
        cpu.setTotal(cpuInfo.getToTal());
        cpu.setWait(cpuInfo.getWait());
        cpu.setFree(cpuInfo.getFree());
        cpu.setUser(cpuInfo.getUser());
        cpu.setUsed(cpuInfo.getUsed());
        cpu.setCpuModel(cpuInfo.getCpuModel());
        return cpu;
    }


    /**
     * 设置内存信息
     */
    public MemInfo memInfo() {
        GlobalMemory memory = OshiUtil.getMemory();
        MemInfo memInfo = new MemInfo();
        long total = memory.getTotal();
        long available = memory.getAvailable();
        memInfo.setTotal(memInfo.cal(total));
        memInfo.setUsed(memInfo.cal(total - available));
        memInfo.setFree(memInfo.cal(available));
        memInfo.setUsage(memInfo.usage());
        return memInfo;
    }

    /**
     * 设置服务器信息
     */
    public SysInfo sysInfo() {
        SysInfo sys = new SysInfo();
        Properties props = System.getProperties();
        sys.setComputerName(NetUtil.getLocalHostName());
        sys.setComputerIp(NetUtil.getLocalhostStr());
        sys.setOsName(props.getProperty("os.name"));
        sys.setOsArch(props.getProperty("os.arch"));
        sys.setUserDir(props.getProperty("user.dir"));
        return sys;
    }

    /**
     * 设置Java虚拟机
     */
    public JvmInfo jvmInfo() {
        JvmInfo jvm = new JvmInfo();
        Properties props = System.getProperties();
        jvm.setTotal(jvm.cal(Runtime.getRuntime().totalMemory()));
        jvm.setMax(jvm.cal(Runtime.getRuntime().maxMemory()));
        jvm.setFree(jvm.cal(Runtime.getRuntime().freeMemory()));
        jvm.setUsed(jvm.getTotal() - jvm.getFree());
        jvm.setUsage(jvm.usage());
        jvm.setVersion(props.getProperty("java.version"));
        jvm.setHome(props.getProperty("java.home"));
        jvm.setStartTime(jvm.startTime());
        jvm.setName(jvm.name());
        jvm.setRunTime(jvm.runTime());
        return jvm;
    }

    /**
     * 设置磁盘信息
     */
    public List<SysFile> sysFiles() {
        SystemInfo si = new SystemInfo();
        OperatingSystem os = si.getOperatingSystem();
        FileSystem fileSystem = os.getFileSystem();
        List<OSFileStore> fsArray = fileSystem.getFileStores();
        List<SysFile> sysFiles = new LinkedList<>();
        for (OSFileStore fs : fsArray) {
            long free = fs.getUsableSpace();
            long total = fs.getTotalSpace();
            long used = total - free;
            SysFile sysFile = new SysFile();
            sysFile.setDirName(fs.getMount());
            sysFile.setSysTypeName(fs.getType());
            sysFile.setTypeName(fs.getName());
            sysFile.setTotal(convertFileSize(total));
            sysFile.setFree(convertFileSize(free));
            sysFile.setUsed(convertFileSize(used));
            sysFile.setUsage(NumberUtil.mul(NumberUtil.div(used, total, 4), 100));
            sysFiles.add(sysFile);
        }
        return sysFiles;
    }

    /**
     * 字节转换
     *
     * @param size 字节大小
     * @return 转换后值
     */
    private String convertFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
        if (size >= gb) {
            return String.format("%.1f GB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        } else {
            return String.format("%d B", size);
        }
    }

    /**
     * 格式化输出大小 B/KB/MB...
     *
     * @param size size
     * @return S
     */
    private String formatData(long size) {
        if (size <= 0L) {
            return "0B";
        } else {
            int digitGroups = Math.min(DataUnit.UNIT_NAMES.length - 1, (int) (Math.log10(size) / Math.log10(1024.0D)));
            return (new DecimalFormat("#,##0.##")).format(size / Math.pow(1024.0D, digitGroups)) + " " + DataUnit.UNIT_NAMES[digitGroups];
        }
    }
}
3.汇总信息封装
package com.mxpt.resource.manage.model;

import lombok.Data;

import java.util.List;

/**
 * @author lfh
 * @description 获取计算机信息;包含cpu、gpu、内存、磁盘、系统、jvm、网络情况
 * @date 2024/3/23 15:11
*/
@Data
public class ComputerInfo {
    /**
     * cpu信息
     */
    private CpuInfo cpuInfo;

    /**
     * gpu信息
     */
    private List<GPUInfo> gpuInfos;

    /**
     * jvm信息
     */
    private JvmInfo jvmInfo;

    /**
     * 内存信息
     */
    private MemInfo memInfo;

    /**
     * 网络情况
     */
    private NetInfo netInfo;

    /**
     * 磁盘
     */
    private List<SysFile> sysFiles;

    /**
     * 系统信息
     */
    private SysInfo sysInfo;
}
4.CPU信息封装
package com.mxpt.resource.manage.model;

import cn.hutool.core.util.NumberUtil;
import lombok.Data;
import java.io.Serializable;

/**
 * @author lfh
 * @description cpu信息读取
 * @date 2024/3/23 14:06
*/
@Data
public class CpuInfo implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 核心数
     */
    private int cpuNum;

    /**
     * CPU总的使用率
     */
    private double total;

    /**
     * CPU系统使用率+%
     */
    private double sys;

    /**
     * CPU用户使用率+%
     */
    private double user;

    /**
     * CPU使用率+%
     */
    private double used;

    /**
     * CPU当前等待率+%
     */
    private double wait;

    /**
     * CPU当前空闲率+%
     */
    private double free;

    /**
     * 型号
     */
    private String cpuModel;
}
5.GPU信息封装
package com.mxpt.resource.manage.model;

import lombok.Data;

/**
 * @author lfh
 * @description GPU信息读取
 * @date 2024/3/23 13:06
*/
@Data
public class GPUInfo {
    int gpuId;

    /**
     * 名称
     */
    String name;

    /**
     * 温度
     */
    int temperature;

    /**
     * 使用占比+%
     */
    int utilization;

    /**
     * 总内存M
     */
    int memoryTotal;

    /**
     * 空闲M
     */
    int memoryFree;

    public GPUInfo(int gpuId, String name, int temperature, int utilization, int memoryTotal, int memoryFree) {
        this.gpuId = gpuId;
        this.name = name;
        this.temperature = temperature;
        this.utilization = utilization;
        this.memoryTotal = memoryTotal;
        this.memoryFree = memoryFree;
    }

    @Override
    public String toString() {
        return "GPU " + gpuId + ": " + name + "\n" +
                "Temperature: " + temperature + " C\n" +
                "Utilization: " + utilization + "%\n" +
                "Memory Total: " + memoryTotal + " MiB\n" +
                "Memory Free: " + memoryFree + " MiB";
    }
}
6.JVM信息封装
package com.mxpt.resource.manage.model;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import lombok.Data;
import java.io.Serializable;
import java.lang.management.ManagementFactory;
import java.util.Date;

/**
 * @author lfh
 * @description JVM信息
 * @date 2024/3/23 15:38
*/
@Data
public class JvmInfo implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 当前JVM占用的内存总数(M)
     */
    private double total;

    /**
     * JVM最大可用内存总数(M)
     */
    private double max;

    /**
     * JVM最大已用内存总数
     */
    private double used;

    /**
     * JVM最大已用内存占比+%
     */
    private double usage;

    /**
     * JVM空闲内存(M)
     */
    private double free;

    /**
     * JDK版本
     */
    private String version;

    /**
     * JDK路径
     */
    private String home;

    /**
     * JDK启动时间
     */
    private String startTime;

    /**
     * JDK运行时间
     */
    private String runTime;

    /**
     * JDK名称
     */
    private String name;

    public double cal(long num) {
        return NumberUtil.div(num, (1024 * 1024), 2);
    }

    public double usage() {
        return NumberUtil.mul(NumberUtil.div(total - free, total, 4), 100);
    }
    /**
     * 获取JDK名称
     */
    public String name() {
        return ManagementFactory.getRuntimeMXBean().getVmName();
    }

    /**
     * JDK启动时间
     */
    public String startTime() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        Date date = new Date(time);
        return DateUtil.formatDateTime(date);
    }

    /**
     * JDK运行时间
     */
    public String runTime() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        Date date = new Date(time);

        //运行多少分钟
        long runMS = DateUtil.between(date, new Date(), DateUnit.MS);

        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;

        long day = runMS / nd;
        long hour = runMS % nd / nh;
        long min = runMS % nd % nh / nm;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    @Override
    public String toString() {
        return "JvmInfo{" +
                "total=" + total +
                ", max=" + max +
                ", used=" + used +
                ", usage=" + usage +
                ", free=" + free +
                ", version='" + version + '\'' +
                ", home='" + home + '\'' +
                ", startTime='" + startTime + '\'' +
                ", runTime='" + runTime + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}
7.内存信息封装
package com.mxpt.resource.manage.model;

import cn.hutool.core.util.NumberUtil;
import lombok.Data;
import java.io.Serializable;

/**
 * @author lfh
 * @description 内存信息读取
 * @date 2024/3/23 14:55
*/
@Data
public class MemInfo implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 内存总量M
     */
    private double total;

    /**
     * 已用内存M
     */
    private double used;

    /**
     * 剩余内存M
     */
    private double free;

    /**
     * 使用率  +%
     */
    private double usage;

    public double cal(double total) {
        return NumberUtil.div(total, (1024 * 1024), 2);
    }

    public double usage() {
        return NumberUtil.mul(NumberUtil.div(used, total, 4),100);
    }
}
8.网络信息封装
package com.mxpt.resource.manage.model;

import lombok.Data;

/**
 * @author lfh
 * @description 网络相关
 * @date 2024/3/23 14:20
*/
@Data
public class NetInfo {

    /**
     * 上行流量
     */
    private String up;

    /**
     * 下行流量
     */
    private String down;
}
9.磁盘信息封装
package com.mxpt.resource.manage.model;

import lombok.Data;
import java.io.Serializable;

/**
 * @author lfh
 * @description 磁盘信息读取
 * @date 2024/3/23 14:56
*/
@Data
public class SysFile implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 盘符路径
     */
    private String dirName;

    /**
     * 盘符类型
     */
    private String sysTypeName;

    /**
     * 文件类型
     */
    private String typeName;

    /**
     * 总大小,会返回单位
     */
    private String total;

    /**
     * 剩余大小
     */
    private String free;

    /**
     * 已经使用量
     */
    private String used;

    /**
     * 资源的使用率+%
     */
    private double usage;
}
10.系统信息封装
package com.mxpt.resource.manage.model;

import lombok.Data;
import java.io.Serializable;

/**
 * @author lfh
 * @description 系统信息读取
 * @date 2024/3/23 14:56
*/
@Data
public class SysInfo implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 服务器名称
     */
    private String computerName;

    /**
     * 服务器Ip
     */
    private String computerIp;

    /**
     * 项目路径
     */
    private String userDir;

    /**
     * 操作系统
     */
    private String osName;

    /**
     * 系统架构
     */
    private String osArch;
}
11.输出结果示例
16:31:40.084 [main] INFO  c.m.r.m.u.SystemUtils - [main,46] - ComputerInfo(cpuInfo=CpuInfo(cpuNum=8, total=8142.0, sys=1.74, user=4.61, used=6.74, wait=0.0, free=93.26, cpuModel=11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
 1 physical CPU package(s)
 4 physical CPU core(s)
 8 logical CPU(s)
Identifier: Intel64 Family 6 Model 140 Stepping 1
ProcessorID: BFEBFBFF000806C1
Microarchitecture: Tiger Lake), gpuInfos=[GPU 0:  NVIDIA GeForce MX450
Temperature: 47 C
Utilization: 0%
Memory Total: 2048 MiB
Memory Free: 1920 MiB], jvmInfo=JvmInfo{total=487.0, max=7205.5, used=97.80000000000001, usage=20.08, free=389.2, version='1.8.0_241', home='D:\software\jdk\jdk8\jre', startTime='2024-03-23 16:31:27', runTime='0天0小时0分钟', name='Java HotSpot(TM) 64-Bit Server VM'}, memInfo=MemInfo(total=32422.65, used=15011.27, free=17411.38, usage=46.3), netInfo=NetInfo(up=0B/s, down=1.95 KB/s), sysFiles=[SysFile(dirName=C:\, sysTypeName=NTFS, typeName=本地固定磁盘 (C:), total=149.2 GB, free=53.2 GB, used=95.9 GB, usage=64.32), SysFile(dirName=D:\, sysTypeName=NTFS, typeName=本地固定磁盘 (D:), total=326.6 GB, free=91.0 GB, used=235.6 GB, usage=72.14)], sysInfo=SysInfo(computerName=LIFUHONG, computerIp=192.168.85.1, userDir=D:\projects\haihe\mxpt-back, osName=Windows 10, osArch=amd64))
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐