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

页面示例

引入对应pom依赖

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

代码示例

java 复制代码
    /**
     * 获取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;
    }

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

java 复制代码
    @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());
        }
    }

获取进行页面展示

java 复制代码
    @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;
    }
相关推荐
海绵波波1071 小时前
Webserver(4.3)TCP通信实现
服务器·网络·tcp/ip
热爱跑步的恒川4 小时前
【论文复现】基于图卷积网络的轻量化推荐模型
网络·人工智能·开源·aigc·ai编程
云飞云共享云桌面5 小时前
8位机械工程师如何共享一台图形工作站算力?
linux·服务器·网络
音徽编程7 小时前
Rust异步运行时框架tokio保姆级教程
开发语言·网络·rust
幺零九零零8 小时前
【C++】socket套接字编程
linux·服务器·网络·c++
23zhgjx-NanKon9 小时前
华为eNSP:QinQ
网络·安全·华为
23zhgjx-NanKon9 小时前
华为eNSP:mux-vlan
网络·安全·华为
点点滴滴的记录9 小时前
RPC核心实现原理
网络·网络协议·rpc
Lionhacker10 小时前
网络工程师这个行业可以一直干到退休吗?
网络·数据库·网络安全·黑客·黑客技术
程思扬10 小时前
为什么Uptime+Kuma本地部署与远程使用是网站监控新选择?
linux·服务器·网络·经验分享·后端·网络协议·1024程序员节