oshi
maven依赖
<dependency> <groupId>com.github.oshi</groupId> <artifactId>oshi-core</artifactId> <version>5.0.0</version> </dependency>
具体实现
package com.demo.oshi.test; import oshi.SystemInfo; import oshi.hardware.*; import oshi.hardware.CentralProcessor.TickType; import oshi.software.os.*; import oshi.software.os.OperatingSystem.ProcessSort; import oshi.util.FormatUtil; import oshi.util.Util; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author :jerry_wei * @date :Created in 2020/5/9 9:15 * @description:cpu监控和内存监控 * @modified By: * @version: */ public class OshiTest { static List<String> oshi = new ArrayList<>(); /** * The main method, demonstrating use of classes. * * @param args * the arguments (unused) */ public static void main(String[] args) { System.out.println("Initializing System..."); SystemInfo si = new SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); OperatingSystem os = si.getOperatingSystem(); printOperatingSystem(os); System.out.println("Checking computer system..."); printComputerSystem(hal.getComputerSystem()); System.out.println("Checking Processor..."); printProcessor(hal.getProcessor()); System.out.println("Checking Memory..."); printMemory(hal.getMemory()); System.out.println("Checking CPU..."); printCpu(hal.getProcessor()); System.out.println("Checking Processes..."); printProcesses(os, hal.getMemory()); System.out.println("Checking Services..."); printServices(os); System.out.println("Checking Sensors..."); printSensors(hal.getSensors()); System.out.println("Checking Power sources..."); printPowerSources(hal.getPowerSources()); System.out.println("Checking Disks..."); printDisks(hal.getDiskStores()); System.out.println("Checking File System..."); printFileSystem(os.getFileSystem()); System.out.println("Checking Network interfaces..."); printNetworkInterfaces(hal.getNetworkIFs()); System.out.println("Checking Network parameters..."); printNetworkParameters(os.getNetworkParams()); System.out.println("Checking IP statistics..."); printInternetProtocolStats(os.getInternetProtocolStats()); // hardware: displays System.out.println("Checking Displays..."); printDisplays(hal.getDisplays()); // hardware: USB devices System.out.println("Checking USB Devices..."); printUsbDevices(hal.getUsbDevices(true)); System.out.println("Checking Sound Cards..."); printSoundCards(hal.getSoundCards()); System.out.println("Checking Graphics Cards..."); printGraphicsCards(hal.getGraphicsCards()); StringBuilder output = new StringBuilder(); for (int i = 0; i < oshi.size(); i++) { output.append(oshi.get(i)); if (oshi.get(i) != null && !oshi.get(i).endsWith("\n")) { output.append('\n'); } } System.out.println("Printing Operating System and Hardware Info:{}{}"+ output); } private static void printOperatingSystem(final OperatingSystem os) { oshi.add(String.valueOf(os)); oshi.add("Booted: " + Instant.ofEpochSecond(os.getSystemBootTime())); oshi.add("Uptime: " + FormatUtil.formatElapsedSecs(os.getSystemUptime())); oshi.add("Running with" + (os.isElevated() ? "" : "out") + " elevated permissions."); } private static void printComputerSystem(final ComputerSystem computerSystem) { oshi.add("system: " + computerSystem.toString()); oshi.add(" firmware: " + computerSystem.getFirmware().toString()); oshi.add(" baseboard: " + computerSystem.getBaseboard().toString()); } private static void printProcessor(CentralProcessor processor) { oshi.add(processor.toString()); } private static void printMemory(GlobalMemory memory) { oshi.add("Physical Memory: \n " + memory.toString()); VirtualMemory vm = memory.getVirtualMemory(); oshi.add("Virtual Memory: \n " + vm.toString()); List<PhysicalMemory> pmList = memory.getPhysicalMemory(); if (!pmList.isEmpty()) { oshi.add("Physical Memory: "); for (PhysicalMemory pm : pmList) { oshi.add(" " + pm.toString()); } } } private static void printCpu(CentralProcessor processor) { oshi.add("Context Switches/Interrupts: " + processor.getContextSwitches() + " / " + processor.getInterrupts()); long[] prevTicks = processor.getSystemCpuLoadTicks(); long[][] prevProcTicks = processor.getProcessorCpuLoadTicks(); oshi.add("CPU, IOWait, and IRQ ticks @ 0 sec:" + Arrays.toString(prevTicks)); // Wait a second... Util.sleep(1000); long[] ticks = processor.getSystemCpuLoadTicks(); oshi.add("CPU, IOWait, and IRQ ticks @ 1 sec:" + Arrays.toString(ticks)); long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()]; long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()]; long sys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()]; long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()]; long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()]; long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()]; long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()]; long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()]; long totalCpu = user + nice + sys + idle + iowait + irq + softirq + steal; oshi.add(String.format( "User: %.1f%% Nice: %.1f%% System: %.1f%% Idle: %.1f%% IOwait: %.1f%% IRQ: %.1f%% SoftIRQ: %.1f%% Steal: %.1f%%", 100d * user / totalCpu, 100d * nice / totalCpu, 100d * sys / totalCpu, 100d * idle / totalCpu, 100d * iowait / totalCpu, 100d * irq / totalCpu, 100d * softirq / totalCpu, 100d * steal / totalCpu)); oshi.add(String.format("CPU load: %.1f%%", processor.getSystemCpuLoadBetweenTicks(prevTicks) * 100)); double[] loadAverage = processor.getSystemLoadAverage(3); oshi.add("CPU load averages:" + (loadAverage[0] < 0 ? " N/A" : String.format(" %.2f", loadAverage[0])) + (loadAverage[1] < 0 ? " N/A" : String.format(" %.2f", loadAverage[1])) + (loadAverage[2] < 0 ? " N/A" : String.format(" %.2f", loadAverage[2]))); // per core CPU StringBuilder procCpu = new StringBuilder("CPU load per processor:"); double[] load = processor.getProcessorCpuLoadBetweenTicks(prevProcTicks); for (double avg : load) { procCpu.append(String.format(" %.1f%%", avg * 100)); } oshi.add(procCpu.toString()); long freq = processor.getProcessorIdentifier().getVendorFreq(); if (freq > 0) { oshi.add("Vendor Frequency: " + FormatUtil.formatHertz(freq)); } freq = processor.getMaxFreq(); if (freq > 0) { oshi.add("Max Frequency: " + FormatUtil.formatHertz(freq)); } long[] freqs = processor.getCurrentFreq(); if (freqs[0] > 0) { StringBuilder sb = new StringBuilder("Current Frequencies: "); for (int i = 0; i < freqs.length; i++) { if (i > 0) { sb.append(", "); } sb.append(FormatUtil.formatHertz(freqs[i])); } oshi.add(sb.toString()); } } private static void printProcesses(OperatingSystem os, GlobalMemory memory) { OSProcess myProc = os.getProcess(os.getProcessId()); oshi.add( "My PID: " + myProc.getProcessID() + " with affinity " + Long.toBinaryString(myProc.getAffinityMask())); oshi.add("Processes: " + os.getProcessCount() + ", Threads: " + os.getThreadCount()); // Sort by highest CPU List<OSProcess> procs = os.getProcesses(5, ProcessSort.CPU); oshi.add(" PID %CPU %MEM VSZ RSS Name"); for (int i = 0; i < procs.size() && i < 5; i++) { OSProcess p = procs.get(i); oshi.add(String.format(" %5d %5.1f %4.1f %9s %9s %s", p.getProcessID(), 100d * (p.getKernelTime() + p.getUserTime()) / p.getUpTime(), 100d * p.getResidentSetSize() / memory.getTotal(), FormatUtil.formatBytes(p.getVirtualSize()), FormatUtil.formatBytes(p.getResidentSetSize()), p.getName())); } } private static void printServices(OperatingSystem os) { oshi.add("Services: "); oshi.add(" PID State Name"); // DO 5 each of running and stopped int i = 0; for (OSService s : os.getServices()) { if (s.getState().equals(OSService.State.RUNNING) && i++ < 5) { oshi.add(String.format(" %5d %7s %s", s.getProcessID(), s.getState(), s.getName())); } } i = 0; for (OSService s : os.getServices()) { if (s.getState().equals(OSService.State.STOPPED) && i++ < 5) { oshi.add(String.format(" %5d %7s %s", s.getProcessID(), s.getState(), s.getName())); } } } private static void printSensors(Sensors sensors) { oshi.add("Sensors: " + sensors.toString()); } private static void printPowerSources(List<PowerSource> list) { StringBuilder sb = new StringBuilder("Power Sources: "); if (list.isEmpty()) { sb.append("Unknown"); } for (PowerSource powerSource : list) { sb.append("\n ").append(powerSource.toString()); } oshi.add(sb.toString()); } private static void printDisks(List<HWDiskStore> list) { oshi.add("Disks:"); for (HWDiskStore disk : list) { oshi.add(" " + disk.toString()); List<HWPartition> partitions = disk.getPartitions(); for (HWPartition part : partitions) { oshi.add(" |-- " + part.toString()); } } } private static void printFileSystem(FileSystem fileSystem) { oshi.add("File System:"); oshi.add(String.format(" File Descriptors: %d/%d", fileSystem.getOpenFileDescriptors(), fileSystem.getMaxFileDescriptors())); for (OSFileStore fs : fileSystem.getFileStores()) { long usable = fs.getUsableSpace(); long total = fs.getTotalSpace(); oshi.add(String.format( " %s (%s) [%s] %s of %s free (%.1f%%), %s of %s files free (%.1f%%) is %s " + (fs.getLogicalVolume() != null && fs.getLogicalVolume().length() > 0 ? "[%s]" : "%s") + " and is mounted at %s", fs.getName(), fs.getDescription().isEmpty() ? "file system" : fs.getDescription(), fs.getType(), FormatUtil.formatBytes(usable), FormatUtil.formatBytes(fs.getTotalSpace()), 100d * usable / total, FormatUtil.formatValue(fs.getFreeInodes(), ""), FormatUtil.formatValue(fs.getTotalInodes(), ""), 100d * fs.getFreeInodes() / fs.getTotalInodes(), fs.getVolume(), fs.getLogicalVolume(), fs.getMount())); } } private static void printNetworkInterfaces(List<NetworkIF> list) { StringBuilder sb = new StringBuilder("Network Interfaces:"); if (list.isEmpty()) { sb.append(" Unknown"); } else { for (NetworkIF net : list) { sb.append("\n ").append(net.toString()); } } oshi.add(sb.toString()); } private static void printNetworkParameters(NetworkParams networkParams) { oshi.add("Network parameters:\n " + networkParams.toString()); } private static void printInternetProtocolStats(InternetProtocolStats ip) { oshi.add("Internet Protocol statistics:"); oshi.add(" TCPv4: " + ip.getTCPv4Stats()); oshi.add(" TCPv6: " + ip.getTCPv6Stats()); oshi.add(" UDPv4: " + ip.getUDPv4Stats()); oshi.add(" UDPv6: " + ip.getUDPv6Stats()); } private static void printDisplays(List<Display> list) { oshi.add("Displays:"); int i = 0; for (Display display : list) { oshi.add(" Display " + i + ":"); oshi.add(String.valueOf(display)); i++; } } private static void printUsbDevices(List<UsbDevice> list) { oshi.add("USB Devices:"); for (UsbDevice usbDevice : list) { oshi.add(String.valueOf(usbDevice)); } } private static void printSoundCards(List<SoundCard> list) { oshi.add("Sound Cards:"); for (SoundCard card : list) { oshi.add(" " + String.valueOf(card)); } } private static void printGraphicsCards(List<GraphicsCard> list) { oshi.add("Graphics Cards:"); if (list.isEmpty()) { oshi.add(" None detected."); } else { for (GraphicsCard card : list) { oshi.add(" " + String.valueOf(card)); } } } }
注意内容
需要继续增加依赖jna,jna-platform,slf4j-api 三个jar包,和spring boot 集成时,springboot本身包含jna包和slf4j包,注意版本问题
sigar
maven依赖
<dependency> <groupId>org.fusesource</groupId> <artifactId>sigar</artifactId> <version>1.6.4</version> </dependency>
具体实现
package com.demo.oshi.test; import org.hyperic.sigar.CpuInfo; import org.hyperic.sigar.CpuPerc; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import java.util.Properties; /** * @author :jerry_wei * @date :Created in 2020/5/8 17:26 * @description:cpu和内存监控类 * @modified By: * @version: */ public class SigarTest { public static void main(String[] args) throws SigarException { cpu(); nei(); } public static void cpu(){ Properties props = System.getProperties(); String systemName = props.getProperty("os.name"); // 使用sigar获取CPU信息及内存 Sigar sigar = new Sigar(); // 获取CPU信息 CpuInfo[] infos = new CpuInfo[0]; try { infos = sigar.getCpuInfoList(); } catch (SigarException e) { e.printStackTrace(); } CpuInfo infoss = infos[0]; CpuPerc cpu = null; try { cpu = sigar.getCpuPerc(); } catch (SigarException e) { e.printStackTrace(); } // CPU总数 Integer totalCPUs = infoss.getTotalCores(); String cpuinfo = infoss.getVendor() + " " + infoss.getModel(); // 获取CPU基准速度 double referenceSpeed = infoss.getMhz(); String referenceSpeeds = String.format("%.2f", referenceSpeed / 1000) + " GHz"; // 获取CPU用户利用率 double userUsedPerc = cpu.getUser(); // 获取CPU系统利用率 double sysUsedPerc = cpu.getSys(); // 获取CPU利用率 double cpuUsedPerc = cpu.getCombined(); String userPers = ""; String sysPers = ""; String cpuPers = ""; if(systemName.startsWith("win") || systemName.startsWith("Win")) { //Windows系统 Perc * 100 userPers = String.format("%.1f", userUsedPerc * 100) + "%"; sysPers = String.format("%.1f", sysUsedPerc * 100) + "%"; cpuPers = String.format("%.1f", cpuUsedPerc * 100) + "%"; }else { //Linux系统 Perc * 1000 cpuPers = String.format("%.1f", cpuUsedPerc * 1000) + "%"; sysPers = String.format("%.1f", sysUsedPerc * 1000) + "%"; userPers = String.format("%.1f", userUsedPerc * 1000) + "%"; } System.out.println("CPU======="+cpuinfo); System.out.println("CPU总数======="+totalCPUs); System.out.println("CPU基准速度======="+referenceSpeeds); System.out.println("CPU用户利用率======="+userPers); System.out.println("CPU系统利用率======="+sysPers); System.out.println("CPU利用率======="+cpuPers); // 关闭sigar sigar.close(); } public static void nei(){ // 使用sigar获取CPU信息及内存 Sigar sigar = new Sigar(); double memTotal = 0; double memRam = 0; double memUsed = 0;// mem double memFree = 0; double memUsedPerc = 0; try { memTotal = sigar.getMem().getTotal(); memRam = sigar.getMem().getRam(); memUsed = sigar.getMem().getActualUsed(); memFree = sigar.getMem().getActualFree(); memUsedPerc = sigar.getMem().getUsedPercent(); } catch (SigarException e) { e.printStackTrace(); } String memory = String.format("%.0f", memTotal / 1024 / 1024 / 1024) + " GB"; String memRamStr = String.format("%.1f", memRam / 1024) + " GB"; String memused = String.format("%.2f", memUsed / 1024 / 1024 / 1024) + " GB"; String memFrees = String.format("%.2f", memFree / 1024 / 1024 / 1024) + " GB"; String memoryUsage = String.format("%.2f", memUsedPerc) + " %"; System.out.println("内存======="+memory); System.out.println("内存使用量======="+memRamStr); System.out.println("使用中======="+memused); System.out.println("可用======="+memFrees); System.out.println("内存使用率======="+memoryUsage); // 关闭sigar sigar.close(); } }
注意问题
需要依赖dll或so文件。
Windows:
系统是64位则把sigar-amd64-winnt.dll添加到C:\Windows\System32
系统是32位则把sigar-x86-winnt.dll添加到C:\Windows\System32
Linux:
把libsigar-amd64-Linux.so(64bit)或libsigar-x86-linux.so(32bit)
添加到/usr/lib64或者/lib64或者/lib或者/usr/lib,只需放其中一个目录