开箱即用之 获取系统的CPU、内存、网络、磁盘使用率

发布时间:2024年01月09日

页面示例

引入对应pom依赖

        <!-- 系统信息相关 -->
        <dependency>
            <groupId>com.github.oshi</groupId>
            <artifactId>oshi-core</artifactId>
            <version>6.4.0</version>
        </dependency>

代码示例

    /**
     * 获取cpu信息
     */
    public static double getCpuInfo() throws InterruptedException
    {
        SystemInfo systemInfo = new SystemInfo();
        CentralProcessor processor = systemInfo.getHardware().getProcessor();
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        // 睡眠1s
        TimeUnit.SECONDS.sleep(1);
        long[] ticks = processor.getSystemCpuLoadTicks();
        long nice = ticks[CentralProcessor.TickType.NICE.getIndex()]
                - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
        long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()]
                - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
        long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()]
                - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
        long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()]
                - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
        long cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()]
                - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
        long user = ticks[CentralProcessor.TickType.USER.getIndex()]
                - prevTicks[CentralProcessor.TickType.USER.getIndex()];
        long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()]
                - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
        long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()]
                - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
        return 1.0 - (idle * 1.0 / totalCpu);
    }

    /**
     * 获取内存使用率
     */
    public static double getMemInfo()
    {
        SystemInfo systemInfo = new SystemInfo();
        GlobalMemory memory = systemInfo.getHardware().getMemory();
        //总内存
        long totalByte = memory.getTotal();
        //剩余
        long acaliableByte = memory.getAvailable();
        return (totalByte - acaliableByte) * 1.0 / totalByte;
    }

    /**
     * 获取网络上传和下载
     */
    public static Map<String, Double> getNetworkInterfaces()
    {
        SystemInfo si = new SystemInfo();
        HardwareAbstractionLayer hal = si.getHardware();
        List<NetworkIF> beforeRecvNetworkIFs = hal.getNetworkIFs();
        NetworkIF beforeBet = beforeRecvNetworkIFs.get(beforeRecvNetworkIFs.size() - 1);
        long beforeRecv = beforeBet.getBytesRecv();
        long beforeSend = beforeBet.getBytesSent();
        try
        {
            Thread.sleep(1000);
        } catch (InterruptedException e)
        {
            logger.error("[线程休眠失败] : {}", e.getMessage());
        }
        List<NetworkIF> afterNetworkIFs = hal.getNetworkIFs();
        NetworkIF afterNet = afterNetworkIFs.get(afterNetworkIFs.size() - 1);

        HashMap<String, Double> map = new HashMap<>();
        // 速度单位: Mbps
        map.put("in", formatUnits(afterNet.getBytesRecv() - beforeRecv, 1048576L));
        map.put("out", formatUnits(afterNet.getBytesSent() - beforeSend, 1048576L));
        return map;
    }

    /**
     * 获取带宽总值
     */
    public static long getNetworkTotal()
    {
        SystemInfo si = new SystemInfo();
        HardwareAbstractionLayer hal = si.getHardware();
        List<NetworkIF> recvNetworkIFs = hal.getNetworkIFs();
        NetworkIF networkIF = recvNetworkIFs.get(recvNetworkIFs.size() - 1);

        return networkIF.getSpeed() / 1048576L / 8L;
    }

    public static double formatUnits(long value, long prefix)
    {
        return (double) value / (double) prefix;
    }

    /**
     * 获取进程数
     */
    public static int getProcessesCount()
    {
        SystemInfo si = new SystemInfo();
        OperatingSystem os = si.getOperatingSystem();

        return os.getProcessCount();
    }

    public static List<Map<String, Object>> getDiskInfo()
    {
        List<Map<String, Object>> result = new ArrayList<>();

        String osName = System.getProperty("os.name");
        List<String> pathArray = new ArrayList<>();
        if (osName.startsWith("Mac OS"))
        {
            // 苹果
            pathArray.add("/");
        } else if (osName.startsWith("Windows"))
        {
            // windows
            pathArray.add("C:");
        } else
        {
            pathArray.add("/");
            pathArray.add("/home");
        }
        for (String path : pathArray)
        {
            Map<String, Object> infoMap = new HashMap<>();
            infoMap.put("path", path);
            File partitionFile = new File(path);
            // 单位: GB
            infoMap.put("use", (partitionFile.getTotalSpace() - partitionFile.getFreeSpace()) / 1024 / 1024 / 1024D);
            infoMap.put("free", partitionFile.getFreeSpace() / 1024 / 1024 / 1024D);
            result.add(infoMap);
        }
        return result;
    }

使用定时任务,去获取实时的系统信息

    @Scheduled(fixedRate = 2000) //每1秒执行一次
    public void execute()
    {
        try
        {
            double cpuInfo = SystemInfoUtils.getCpuInfo();
            redisCatchStorage.addCpuInfo(cpuInfo);
            double memInfo = SystemInfoUtils.getMemInfo();
            redisCatchStorage.addMemInfo(memInfo);
            Map<String, Double> networkInterfaces = SystemInfoUtils.getNetworkInterfaces();
            redisCatchStorage.addNetInfo(networkInterfaces);
            List<Map<String, Object>> diskInfo = SystemInfoUtils.getDiskInfo();
            redisCatchStorage.addDiskInfo(diskInfo);
        } catch (InterruptedException e)
        {
            logger.error("[获取系统信息失败] {}", e.getMessage());
        }
    }

获取进行页面展示

    @Override
    public SystemAllInfo getSystemInfo()
    {
        String cpuKey = GlobalConfig.SYSTEM_INFO_CPU_PREFIX;
        String memKey = GlobalConfig.SYSTEM_INFO_MEM_PREFIX;
        String netKey = GlobalConfig.SYSTEM_INFO_NET_PREFIX;
        String diskKey = GlobalConfig.SYSTEM_INFO_DISK_PREFIX;
        String npuKey = GlobalConfig.SYSTEM_INFO_NPU_PREFIX;
        SystemAllInfo systemAllInfo = new SystemAllInfo();
        systemAllInfo.setCpu(redisTemplate.opsForList().range(cpuKey, 0, -1));
        systemAllInfo.setMem(redisTemplate.opsForList().range(memKey, 0, -1));
        systemAllInfo.setNet(redisTemplate.opsForList().range(netKey, 0, -1));
        systemAllInfo.setDisk(redisTemplate.opsForValue().get(diskKey));
        systemAllInfo.setNetTotal(SystemInfoUtils.getNetworkTotal());
        return systemAllInfo;
    }

文章来源:https://blog.csdn.net/2301_76354366/article/details/135484828
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。