首页

基于oshi-core实现系统硬件内存、cpu及负载网络流量数据收集代码示例

标签:oshi,服务器     发布时间:2023-10-19   

一、前言

通过oshi-core的工具包获取操作系统信息、文件系统信息、cpu信息、内存信息、网络流量信息及系统负载信息代码示例。

二、代码示例

package com.wgcloud;@b@ @b@ @b@import cn.hutool.json.JSONArray;@b@import cn.hutool.json.JSONObject;@b@import cn.hutool.json.JSONUtil;@b@import com.wgcloud.entity.*;@b@import org.apache.commons.lang3.StringUtils;@b@import org.slf4j.Logger;@b@import org.slf4j.LoggerFactory;@b@import org.springframework.beans.factory.annotation.Autowired;@b@import org.springframework.scheduling.annotation.Scheduled;@b@import org.springframework.stereotype.Component;@b@import oshi.hardware.HardwareAbstractionLayer;@b@import oshi.software.os.OperatingSystem;@b@ @b@import java.sql.Timestamp;@b@import java.util.ArrayList;@b@import java.util.Collections;@b@import java.util.List;@b@import java.util.concurrent.LinkedBlockingDeque;@b@import java.util.concurrent.ThreadPoolExecutor;@b@import java.util.concurrent.TimeUnit;@b@ @b@/**@b@ * @version V2.3@b@ * @ClassName:ScheduledTask.java@b@ * @author: wgcloud@b@ * @date: 2019年11月16日@b@ * @Description: ScheduledTask.java@b@ * @Copyright: 2017-2023 www.wgstart.com. All rights reserved.@b@ */@b@@Component@b@public class ScheduledTask {@b@ @b@    private Logger logger = LoggerFactory.getLogger(ScheduledTask.class);@b@    public static List<AppInfo> appInfoList = Collections.synchronizedList(new ArrayList<AppInfo>());@b@    @Autowired@b@    private RestUtil restUtil;@b@    @Autowired@b@    private CommonConfig commonConfig;@b@ @b@    private SystemInfo systemInfo = null;@b@ @b@ @b@    /**@b@     * 线程池@b@     */@b@    static ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 2, TimeUnit.MINUTES, new LinkedBlockingDeque<>());@b@ @b@    /**@b@     * 60秒后执行,每隔120秒执行, 单位:ms。@b@     */@b@    @Scheduled(initialDelay = 59 * 1000L, fixedRate = 120 * 1000)@b@    public void minTask() {@b@        List<AppInfo> APP_INFO_LIST_CP = new ArrayList<AppInfo>();@b@        APP_INFO_LIST_CP.addAll(appInfoList);@b@        JSONObject jsonObject = new JSONObject();@b@        LogInfo logInfo = new LogInfo();@b@        Timestamp t = FormatUtil.getNowTime();@b@        logInfo.setHostname(commonConfig.getBindIp() + ":Agent错误");@b@        logInfo.setCreateTime(t);@b@        try {@b@            oshi.SystemInfo si = new oshi.SystemInfo();@b@ @b@            HardwareAbstractionLayer hal = si.getHardware();@b@            OperatingSystem os = si.getOperatingSystem();@b@ @b@            // 操作系统信息@b@            systemInfo = OshiUtil.os(hal.getProcessor(), os);@b@            systemInfo.setCreateTime(t);@b@            // 文件系统信息@b@            List<DeskState> deskStateList = OshiUtil.file(t, os.getFileSystem());@b@            // cpu信息@b@            CpuState cpuState = OshiUtil.cpu(hal.getProcessor());@b@            cpuState.setCreateTime(t);@b@            // 内存信息@b@            MemState memState = OshiUtil.memory(hal.getMemory());@b@            memState.setCreateTime(t);@b@            // 网络流量信息@b@            NetIoState netIoState = OshiUtil.net(hal);@b@            netIoState.setCreateTime(t);@b@            // 系统负载信息@b@            SysLoadState sysLoadState = OshiUtil.getLoadState(systemInfo, hal.getProcessor());@b@            if (sysLoadState != null) {@b@                sysLoadState.setCreateTime(t);@b@            }@b@            if (cpuState != null) {@b@                jsonObject.put("cpuState", cpuState);@b@            }@b@            if (memState != null) {@b@                jsonObject.put("memState", memState);@b@            }@b@            if (netIoState != null) {@b@                jsonObject.put("netIoState", netIoState);@b@            }@b@            if (sysLoadState != null) {@b@                jsonObject.put("sysLoadState", sysLoadState);@b@            }@b@            if (systemInfo != null) {@b@                if (memState != null) {@b@                    systemInfo.setVersionDetail(systemInfo.getVersion() + ",总内存:" + oshi.util.FormatUtil.formatBytes(hal.getMemory().getTotal()));@b@                    systemInfo.setMemPer(memState.getUsePer());@b@                } else {@b@                    systemInfo.setMemPer(0d);@b@                }@b@                if (cpuState != null) {@b@                    systemInfo.setCpuPer(cpuState.getSys());@b@                } else {@b@                    systemInfo.setCpuPer(0d);@b@                }@b@                jsonObject.put("systemInfo", systemInfo);@b@            }@b@            if (deskStateList != null) {@b@                jsonObject.put("deskStateList", deskStateList);@b@            }@b@            //进程信息@b@            if (APP_INFO_LIST_CP.size() > 0) {@b@                List<AppInfo> appInfoResList = new ArrayList<>();@b@                List<AppState> appStateResList = new ArrayList<>();@b@                for (AppInfo appInfo : APP_INFO_LIST_CP) {@b@                    appInfo.setHostname(commonConfig.getBindIp());@b@                    appInfo.setCreateTime(t);@b@                    appInfo.setState("1");@b@                    String pid = FormatUtil.getPidByFile(appInfo);@b@                    if (StringUtils.isEmpty(pid)) {@b@                        continue;@b@                    }@b@                    AppState appState = OshiUtil.getLoadPid(pid, os, hal.getMemory());@b@                    if (appState != null) {@b@                        appState.setCreateTime(t);@b@                        appState.setAppInfoId(appInfo.getId());@b@                        appInfo.setMemPer(appState.getMemPer());@b@                        appInfo.setCpuPer(appState.getCpuPer());@b@                        appInfoResList.add(appInfo);@b@                        appStateResList.add(appState);@b@                    }@b@                }@b@                jsonObject.put("appInfoList", appInfoResList);@b@                jsonObject.put("appStateList", appStateResList);@b@            }@b@ @b@            logger.debug("---------------" + jsonObject.toString());@b@        } catch (Exception e) {@b@            e.printStackTrace();@b@            logInfo.setInfoContent(e.toString());@b@        } finally {@b@            if (!StringUtils.isEmpty(logInfo.getInfoContent())) {@b@                jsonObject.put("logInfo", logInfo);@b@            }@b@            restUtil.post(commonConfig.getServerUrl() + "/wgcloud/agent/minTask", jsonObject);@b@        }@b@ @b@    }@b@ @b@ @b@    /**@b@     * 30秒后执行,每隔5分钟执行, 单位:ms。@b@     * 获取监控进程@b@     */@b@    @Scheduled(initialDelay = 28 * 1000L, fixedRate = 300 * 1000)@b@    public void appInfoListTask() {@b@        JSONObject jsonObject = new JSONObject();@b@        LogInfo logInfo = new LogInfo();@b@        Timestamp t = FormatUtil.getNowTime();@b@        logInfo.setHostname(commonConfig.getBindIp() + ":Agent获取进程列表错误");@b@        logInfo.setCreateTime(t);@b@        try {@b@            JSONObject paramsJson = new JSONObject();@b@            paramsJson.put("hostname", commonConfig.getBindIp());@b@            String resultJson = restUtil.post(commonConfig.getServerUrl() + "/wgcloud/appInfo/agentList", paramsJson);@b@            if (resultJson != null) {@b@                JSONArray resultArray = JSONUtil.parseArray(resultJson);@b@                appInfoList.clear();@b@                if (resultArray.size() > 0) {@b@                    appInfoList = JSONUtil.toList(resultArray, AppInfo.class);@b@                }@b@            }@b@        } catch (Exception e) {@b@            e.printStackTrace();@b@            logInfo.setInfoContent(e.toString());@b@        } finally {@b@            if (!StringUtils.isEmpty(logInfo.getInfoContent())) {@b@                jsonObject.put("logInfo", logInfo);@b@            }@b@            restUtil.post(commonConfig.getServerUrl() + "/wgcloud/agent/minTask", jsonObject);@b@        }@b@    }@b@ @b@ @b@}