java 获取内存 cpu 磁盘的使用情况

问题描述

目前线上的服务越来越多,需要监控对应服务的运行状态和系统基本信息:磁盘,cpu,内存的使用情况,线上服务和本地环境的机器类型不同,查找相关资料未找到可用的代码,经过查找相关资料,整理如下。

使用oshi

1.需要导入的包

<!--系统使用率导包开始-->
       <dependency>  <!--工具类 小数格式化 可以改为其他-->
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.0.9</version>
        </dependency>
        <dependency>
            <groupId>net.java.dev.jna</groupId>
            <artifactId>jna</artifactId>
            <version>4.5.0</version>
        </dependency>
        <dependency>
            <groupId>net.java.dev.jna</groupId>
            <artifactId>jna-platform</artifactId>
            <version>4.5.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.github.oshi/oshi-json -->
        <dependency>
            <groupId>com.github.oshi</groupId>
            <artifactId>oshi-json</artifactId>
            <version>3.6.1</version>
        </dependency>
        <!--系统使用率导包结束-->

2.上干活 具体代码

这里获取磁盘使用情况在linux下有问题,所以使用了其他的方式获取

import java.io.InputStreamReader;
import java.io.LineNumberReader;

import cn.hutool.core.util.NumberUtil;
import lombok.extern.slf4j.Slf4j;
import oshi.json.SystemInfo;
import oshi.json.hardware.CentralProcessor;
import oshi.json.hardware.GlobalMemory;
import oshi.json.hardware.HWDiskStore;
import oshi.json.hardware.HardwareAbstractionLayer;

/**
 * <p>
 * 类说明
 * </p>
 *
 * @author Shawn
 * @since 2018/06/29
 */
@Slf4j
public class SystemUsageUtil {

    private static SystemInfo systemInfo = new SystemInfo();

    /**
     * 获取内存的使用率
     *
     * @return 内存使用率 0.36
     */
    public static double getMemoryUsage() {
        HardwareAbstractionLayer hal = systemInfo.getHardware();
        GlobalMemory memory = hal.getMemory();
        long available = memory.getAvailable();
        long total = memory.getTotal();
        log.info("getMemoryUsage available={},total={}", available, total);
        double useRate = NumberUtil.div(available, total, 2);
        return useRate;
    }

    /**
     * 获取CPU的使用率
     *
     * @return CPU使用率 0.36
     */
    public static double getCpuUsage() {
        HardwareAbstractionLayer hal = systemInfo.getHardware();
        CentralProcessor processor = hal.getProcessor();
        double useRate = processor.getSystemCpuLoadBetweenTicks();
        log.info("getCpuUsage useRate={}", useRate);
        return NumberUtil.div(useRate, 1, 2);
    }

    /**
     * 获取磁盘的使用率
     *
     * @return CPU使用率 0.36
     */
    public static double getDiskUsage() {
        if (isWindows()) {
            return getWinDiskUsage();
        }
        return getUnixDiskUsage();
    }


    /**
     * 判断系统是否为windows
     *
     * @return 是否
     */
    private static boolean isWindows() {
        return System.getProperties().getProperty("os.name").toUpperCase().contains("WINDOWS");
    }

    /**
     * 获取linux 磁盘使用率
     *
     * @return 磁盘使用率
     */
    private static double getUnixDiskUsage() {
        String ioCmdStr = "df -h /";
        String resultInfo = runCommand(ioCmdStr);
        String[] data = resultInfo.split(" +");
        double total = Double.parseDouble(data[10].replace("%", ""));
        return total / 100;
    }

    /**
     * 获取linux 磁盘使用率
     *
     * @return 磁盘使用率
     */
    private static double getWinDiskUsage() {

        HardwareAbstractionLayer hal = systemInfo.getHardware();
        HWDiskStore[] diskStores = hal.getDiskStores();
        long total = 0;
        long used = 0;
        if (diskStores != null && diskStores.length > 0) {
            for (HWDiskStore diskStore : diskStores) {
                long size = diskStore.getSize();
                long writeBytes = diskStore.getWriteBytes();
                total += size;
                used += writeBytes;
            }
        }
        return NumberUtil.div(used, total, 2);
    }


    /**
     * 执行系统命令
     *
     * @param CMD 命令
     * @return 字符串结果
     */
    private static String runCommand(String CMD) {
        StringBuilder info = new StringBuilder();
        try {
            Process pos = Runtime.getRuntime().exec(CMD);
            pos.waitFor();
            InputStreamReader isr = new InputStreamReader(pos.getInputStream());
            LineNumberReader lnr = new LineNumberReader(isr);
            String line;
            while ((line = lnr.readLine()) != null) {
                info.append(line).append("\n");
            }
        } catch (Exception e) {
            info = new StringBuilder(e.toString());
        }
        return info.toString();
    }
}

亲测 linux和windows环境可正常使用

参考资料

https://github.com/oshi/oshi

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 关于Mongodb的全面总结 MongoDB的内部构造《MongoDB The Definitive Guide》...
    中v中阅读 32,016评论 2 89
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,242评论 25 708
  • 一天转战四个场地,工作加学习,披星戴月走回家。看着满屏的圣诞庆祝活动,我只想啃个苹果,看个电视剧。 感谢伙伴们的礼物。
    Anne_GG阅读 96评论 0 0
  • 怎么说,今天发生的一幕让我觉得异常难过。 因为下雨天,我闲来无聊,盯着窗子外面,看淅淅沥沥的雨下个不停,不经意间看...
    松下的瑜阅读 268评论 3 5
  • washingaway阅读 138评论 0 0