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

页面示例

开箱即用之 获取系统的CPU、内存、网络、磁盘使用率_第1张图片

引入对应pom依赖

        
        
            com.github.oshi
            oshi-core
            6.4.0
        

代码示例

    /**
     * 获取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 getNetworkInterfaces()
    {
        SystemInfo si = new SystemInfo();
        HardwareAbstractionLayer hal = si.getHardware();
        List 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 afterNetworkIFs = hal.getNetworkIFs();
        NetworkIF afterNet = afterNetworkIFs.get(afterNetworkIFs.size() - 1);

        HashMap 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 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> getDiskInfo()
    {
        List> result = new ArrayList<>();

        String osName = System.getProperty("os.name");
        List 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 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 networkInterfaces = SystemInfoUtils.getNetworkInterfaces();
            redisCatchStorage.addNetInfo(networkInterfaces);
            List> 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;
    }

你可能感兴趣的:(开箱即用,网络,驱动开发)