SpringBoot集成oshi 查询系统数据
SpringBoot集成oshi查询系统数据
·
实现功能:
<!-- 获取系统信息 -->
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>6.6.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.16.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.14.0</version> <!-- 可替换为最新版本 -->
</dependency>
<!-- 解析客户端操作系统、浏览器等 -->
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>1.21</version>
</dependency>
package com.example.springbootai.entity.server;
import com.example.springbootai.utils.Arith;
/**
* CPU相关信息
*
* @author caojun
*/
public class Cpu
{
/**
* 核心数
*/
private int cpuNum;
/**
* CPU总的使用率
*/
private double total;
/**
* CPU系统使用率
*/
private double sys;
/**
* CPU用户使用率
*/
private double used;
/**
* CPU当前等待率
*/
private double wait;
/**
* CPU当前空闲率
*/
private double free;
public int getCpuNum()
{
return cpuNum;
}
public void setCpuNum(int cpuNum)
{
this.cpuNum = cpuNum;
}
public double getTotal()
{
return Arith.round(Arith.mul(total, 100), 2);
}
public void setTotal(double total)
{
this.total = total;
}
public double getSys()
{
return Arith.round(Arith.mul(sys / total, 100), 2);
}
public void setSys(double sys)
{
this.sys = sys;
}
public double getUsed()
{
return Arith.round(Arith.mul(used / total, 100), 2);
}
public void setUsed(double used)
{
this.used = used;
}
public double getWait()
{
return Arith.round(Arith.mul(wait / total, 100), 2);
}
public void setWait(double wait)
{
this.wait = wait;
}
public double getFree()
{
return Arith.round(Arith.mul(free / total, 100), 2);
}
public void setFree(double free)
{
this.free = free;
}
}
package com.example.springbootai.entity.server;
import com.example.springbootai.utils.Arith;
import com.example.springbootai.utils.DateUtils;
import java.lang.management.ManagementFactory;
/**
* JVM相关信息
*
* @author caojun
*/
public class Jvm
{
/**
* 当前JVM占用的内存总数(M)
*/
private double total;
/**
* JVM最大可用内存总数(M)
*/
private double max;
/**
* JVM空闲内存(M)
*/
private double free;
/**
* JDK版本
*/
private String version;
/**
* JDK路径
*/
private String home;
public double getTotal()
{
return Arith.div(total, (1024 * 1024), 2);
}
public void setTotal(double total)
{
this.total = total;
}
public double getMax()
{
return Arith.div(max, (1024 * 1024), 2);
}
public void setMax(double max)
{
this.max = max;
}
public double getFree()
{
return Arith.div(free, (1024 * 1024), 2);
}
public void setFree(double free)
{
this.free = free;
}
public double getUsed()
{
return Arith.div(total - free, (1024 * 1024), 2);
}
public double getUsage()
{
return Arith.mul(Arith.div(total - free, total, 4), 100);
}
/**
* 获取JDK名称
*/
public String getName()
{
return ManagementFactory.getRuntimeMXBean().getVmName();
}
public String getVersion()
{
return version;
}
public void setVersion(String version)
{
this.version = version;
}
public String getHome()
{
return home;
}
public void setHome(String home)
{
this.home = home;
}
/**
* JDK启动时间
*/
public String getStartTime()
{
return DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getServerStartDate());
}
/**
* JDK运行时间
*/
public String getRunTime()
{
return DateUtils.timeDistance(DateUtils.getNowDate(), DateUtils.getServerStartDate());
}
/**
* 运行参数
*/
public String getInputArgs()
{
return ManagementFactory.getRuntimeMXBean().getInputArguments().toString();
}
}
package com.example.springbootai.entity.server;
import com.example.springbootai.utils.Arith;
/**
* 內存相关信息
*
* @author caojun
*/
public class Mem
{
/**
* 内存总量
*/
private double total;
/**
* 已用内存
*/
private double used;
/**
* 剩余内存
*/
private double free;
public double getTotal()
{
return Arith.div(total, (1024 * 1024 * 1024), 2);
}
public void setTotal(long total)
{
this.total = total;
}
public double getUsed()
{
return Arith.div(used, (1024 * 1024 * 1024), 2);
}
public void setUsed(long used)
{
this.used = used;
}
public double getFree()
{
return Arith.div(free, (1024 * 1024 * 1024), 2);
}
public void setFree(long free)
{
this.free = free;
}
public double getUsage()
{
return Arith.mul(Arith.div(used, total, 4), 100);
}
}
package com.example.springbootai.entity.server;
/**
* 系统相关信息
*
* @author caojun
*/
public class Sys
{
/**
* 服务器名称
*/
private String computerName;
/**
* 服务器Ip
*/
private String computerIp;
/**
* 项目路径
*/
private String userDir;
/**
* 操作系统
*/
private String osName;
/**
* 系统架构
*/
private String osArch;
public String getComputerName()
{
return computerName;
}
public void setComputerName(String computerName)
{
this.computerName = computerName;
}
public String getComputerIp()
{
return computerIp;
}
public void setComputerIp(String computerIp)
{
this.computerIp = computerIp;
}
public String getUserDir()
{
return userDir;
}
public void setUserDir(String userDir)
{
this.userDir = userDir;
}
public String getOsName()
{
return osName;
}
public void setOsName(String osName)
{
this.osName = osName;
}
public String getOsArch()
{
return osArch;
}
public void setOsArch(String osArch)
{
this.osArch = osArch;
}
}
package com.example.springbootai.entity.server;
/**
* 系统文件相关信息
*
* @author ruoyi
*/
public class SysFile
{
/**
* 盘符路径
*/
private String dirName;
/**
* 盘符类型
*/
private String sysTypeName;
/**
* 文件类型
*/
private String typeName;
/**
* 总大小
*/
private String total;
/**
* 剩余大小
*/
private String free;
/**
* 已经使用量
*/
private String used;
/**
* 资源的使用率
*/
private double usage;
public String getDirName()
{
return dirName;
}
public void setDirName(String dirName)
{
this.dirName = dirName;
}
public String getSysTypeName()
{
return sysTypeName;
}
public void setSysTypeName(String sysTypeName)
{
this.sysTypeName = sysTypeName;
}
public String getTypeName()
{
return typeName;
}
public void setTypeName(String typeName)
{
this.typeName = typeName;
}
public String getTotal()
{
return total;
}
public void setTotal(String total)
{
this.total = total;
}
public String getFree()
{
return free;
}
public void setFree(String free)
{
this.free = free;
}
public String getUsed()
{
return used;
}
public void setUsed(String used)
{
this.used = used;
}
public double getUsage()
{
return usage;
}
public void setUsage(double usage)
{
this.usage = usage;
}
}
package com.example.springbootai.entity;
import java.net.UnknownHostException;
import java.util.*;
import com.example.springbootai.entity.server.*;
import com.example.springbootai.utils.Arith;
import oshi.SystemInfo;
import oshi.hardware.*;
import oshi.hardware.CentralProcessor.TickType;
import oshi.software.os.*;
import oshi.util.Util;
/**
* 服务器相关信息
*
* @author caojun
*/
public class Server
{
private static final int OSHI_WAIT_SECOND = 1000;
/**
* CPU相关信息
*/
private Cpu cpu = new Cpu();
/**
* 內存相关信息
*/
private Mem mem = new Mem();
/**
* JVM相关信息
*/
private Jvm jvm = new Jvm();
/**
* 服务器相关信息
*/
private Sys sys = new Sys();
/**
* 磁盘相关信息
*/
private List<SysFile> sysFiles = new LinkedList<SysFile>();
public Cpu getCpu()
{
return cpu;
}
public void setCpu(Cpu cpu)
{
this.cpu = cpu;
}
public Mem getMem()
{
return mem;
}
public void setMem(Mem mem)
{
this.mem = mem;
}
public Jvm getJvm()
{
return jvm;
}
public void setJvm(Jvm jvm)
{
this.jvm = jvm;
}
public Sys getSys()
{
return sys;
}
public void setSys(Sys sys)
{
this.sys = sys;
}
public List<SysFile> getSysFiles()
{
return sysFiles;
}
public void setSysFiles(List<SysFile> sysFiles)
{
this.sysFiles = sysFiles;
}
public void copyTo() throws Exception
{
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
setCpuInfo(hal.getProcessor());
setMemInfo(hal.getMemory());
setSysInfo();
setJvmInfo();
setSysFiles(si.getOperatingSystem());
}
/**
* 设置CPU信息
*/
private void setCpuInfo(CentralProcessor processor)
{
// CPU信息
long[] prevTicks = processor.getSystemCpuLoadTicks();
Util.sleep(OSHI_WAIT_SECOND);
long[] ticks = processor.getSystemCpuLoadTicks();
long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.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 cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
cpu.setCpuNum(processor.getLogicalProcessorCount());
cpu.setTotal(totalCpu);
cpu.setSys(cSys);
cpu.setUsed(user);
cpu.setWait(iowait);
cpu.setFree(idle);
}
/**
* 设置内存信息
*/
private void setMemInfo(GlobalMemory memory)
{
mem.setTotal(memory.getTotal());
mem.setUsed(memory.getTotal() - memory.getAvailable());
mem.setFree(memory.getAvailable());
}
/**
* 设置服务器信息
*/
private void setSysInfo()
{
Properties props = System.getProperties();
sys.setOsName(props.getProperty("os.name"));
sys.setOsArch(props.getProperty("os.arch"));
sys.setUserDir(props.getProperty("user.dir"));
}
/**
* 设置Java虚拟机
*/
private void setJvmInfo() throws UnknownHostException
{
Properties props = System.getProperties();
jvm.setTotal(Runtime.getRuntime().totalMemory());
jvm.setMax(Runtime.getRuntime().maxMemory());
jvm.setFree(Runtime.getRuntime().freeMemory());
jvm.setVersion(props.getProperty("java.version"));
jvm.setHome(props.getProperty("java.home"));
}
/**
* 设置磁盘信息
*/
private void setSysFiles(OperatingSystem os)
{
FileSystem fileSystem = os.getFileSystem();
List<OSFileStore> fsArray = fileSystem.getFileStores();
for (OSFileStore fs : fsArray)
{
long free = fs.getUsableSpace();
long total = fs.getTotalSpace();
long used = total - free;
SysFile sysFile = new SysFile();
sysFile.setDirName(fs.getMount());
sysFile.setSysTypeName(fs.getType());
sysFile.setTypeName(fs.getName());
sysFile.setTotal(convertFileSize(total));
sysFile.setFree(convertFileSize(free));
sysFile.setUsed(convertFileSize(used));
sysFile.setUsage(Arith.mul(Arith.div(used, total, 4), 100));
sysFiles.add(sysFile);
}
}
/**
* 字节转换
*
* @param size 字节大小
* @return 转换后值
*/
public String convertFileSize(long size)
{
long kb = 1024;
long mb = kb * 1024;
long gb = mb * 1024;
if (size >= gb)
{
return String.format("%.1f GB", (float) size / gb);
}
else if (size >= mb)
{
float f = (float) size / mb;
return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
}
else if (size >= kb)
{
float f = (float) size / kb;
return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
}
else
{
return String.format("%d B", size);
}
}
}
两个工具类
package com.example.springbootai.utils;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* 精确的浮点数运算
*
* @author caojun
*/
public class Arith
{
/** 默认除法运算精度 */
private static final int DEF_DIV_SCALE = 10;
/** 这个类不能实例化 */
private Arith()
{
}
/**
* 提供精确的加法运算。
* @param v1 被加数
* @param v2 加数
* @return 两个参数的和
*/
public static double add(double v1, double v2)
{
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
/**
* 提供精确的减法运算。
* @param v1 被减数
* @param v2 减数
* @return 两个参数的差
*/
public static double sub(double v1, double v2)
{
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
/**
* 提供精确的乘法运算。
* @param v1 被乘数
* @param v2 乘数
* @return 两个参数的积
*/
public static double mul(double v1, double v2)
{
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}
/**
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到
* 小数点以后10位,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @return 两个参数的商
*/
public static double div(double v1, double v2)
{
return div(v1, v2, DEF_DIV_SCALE);
}
/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
* 定精度,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @param scale 表示表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public static double div(double v1, double v2, int scale)
{
if (scale < 0)
{
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
if (b1.compareTo(BigDecimal.ZERO) == 0)
{
return BigDecimal.ZERO.doubleValue();
}
return b1.divide(b2, scale, RoundingMode.HALF_UP).doubleValue();
}
/**
* 提供精确的小数位四舍五入处理。
* @param v 需要四舍五入的数字
* @param scale 小数点后保留几位
* @return 四舍五入后的结果
*/
public static double round(double v, int scale)
{
if (scale < 0)
{
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = BigDecimal.ONE;
return b.divide(one, scale, RoundingMode.HALF_UP).doubleValue();
}
}
package com.example.springbootai.utils;
import org.apache.commons.lang3.time.DateFormatUtils;
import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.Date;
/**
* 时间工具类
*
* @author caojun
*/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
public static String YYYY = "yyyy";
public static String YYYY_MM = "yyyy-MM";
public static String YYYY_MM_DD = "yyyy-MM-dd";
public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
private static String[] parsePatterns = {
"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
/**
* 获取当前Date型日期
*
* @return Date() 当前日期
*/
public static Date getNowDate()
{
return new Date();
}
/**
* 获取当前日期, 默认格式为yyyy-MM-dd
*
* @return String
*/
public static String getDate()
{
return dateTimeNow(YYYY_MM_DD);
}
public static final String getTime()
{
return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
}
public static final String dateTimeNow()
{
return dateTimeNow(YYYYMMDDHHMMSS);
}
public static final String dateTimeNow(final String format)
{
return parseDateToStr(format, new Date());
}
public static final String dateTime(final Date date)
{
return parseDateToStr(YYYY_MM_DD, date);
}
public static final String parseDateToStr(final String format, final Date date)
{
return new SimpleDateFormat(format).format(date);
}
public static final Date dateTime(final String format, final String ts)
{
try
{
return new SimpleDateFormat(format).parse(ts);
}
catch (ParseException e)
{
throw new RuntimeException(e);
}
}
/**
* 日期路径 即年/月/日 如2018/08/08
*/
public static final String datePath()
{
Date now = new Date();
return DateFormatUtils.format(now, "yyyy/MM/dd");
}
/**
* 日期路径 即年/月/日 如20180808
*/
public static final String dateTime()
{
Date now = new Date();
return DateFormatUtils.format(now, "yyyyMMdd");
}
/**
* 日期型字符串转化为日期 格式
*/
public static Date parseDate(Object str)
{
if (str == null)
{
return null;
}
try
{
return parseDate(str.toString(), parsePatterns);
}
catch (ParseException e)
{
return null;
}
}
/**
* 获取服务器启动时间
*/
public static Date getServerStartDate()
{
long time = ManagementFactory.getRuntimeMXBean().getStartTime();
return new Date(time);
}
/**
* 计算相差天数
*/
public static int differentDaysByMillisecond(Date date1, Date date2)
{
return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
}
/**
* 计算时间差
*
* @param endDate 最后时间
* @param startTime 开始时间
* @return 时间差(天/小时/分钟)
*/
public static String timeDistance(Date endDate, Date startTime)
{
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
// long ns = 1000;
// 获得两个时间的毫秒时间差异
long diff = endDate.getTime() - startTime.getTime();
// 计算差多少天
long day = diff / nd;
// 计算差多少小时
long hour = diff % nd / nh;
// 计算差多少分钟
long min = diff % nd % nh / nm;
// 计算差多少秒//输出结果
// long sec = diff % nd % nh % nm / ns;
return day + "天" + hour + "小时" + min + "分钟";
}
/**
* 增加 LocalDateTime ==> Date
*/
public static Date toDate(LocalDateTime temporalAccessor)
{
ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
return Date.from(zdt.toInstant());
}
/**
* 增加 LocalDate ==> Date
*/
public static Date toDate(LocalDate temporalAccessor)
{
LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
return Date.from(zdt.toInstant());
}
}
package com.example.springbootai;
import oshi.SystemInfo;
import oshi.hardware.*;
import oshi.software.os.OSFileStore;
import oshi.software.os.OSProcess;
import oshi.software.os.OperatingSystem;
import oshi.util.FormatUtil;
import oshi.util.Util;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
* @title: test
* @Author CaoJun
* @Date: 2025/4/18 下午4:40
* @Version 1.0
*/
public class test {
public static void main(String[] args) {
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
OperatingSystem os = si.getOperatingSystem();
// 1. 操作系统信息
printOperatingSystemInfo(os);
// 2. 计算机系统信息
printComputerSystemInfo(hal.getComputerSystem());
// 3. CPU信息
printCpuInfo(hal.getProcessor());
// 4. 内存信息
printMemoryInfo(hal.getMemory());
// 5. 磁盘信息
printDiskInfo(hal.getDiskStores());
// 6. 文件系统信息
printFileSystemInfo(os.getFileSystem().getFileStores());
// 7. 网络信息
printNetworkInfo(hal.getNetworkIFs());
// 8. 显卡信息
printGraphicsInfo(hal.getGraphicsCards());
// 9. 传感器信息
printSensorsInfo(hal.getSensors());
// 10. 电源信息
printPowerInfo(hal.getPowerSources());
// 11. 进程信息
printProcessInfo(os.getProcesses());
}
private static void printOperatingSystemInfo(OperatingSystem os) {
System.out.println("\n=== 操作系统信息 ===");
System.out.println("操作系统: " + os.toString());
System.out.println("制造商: " + os.getManufacturer());
System.out.println("系列: " + os.getFamily());
System.out.println("版本: " + os.getVersionInfo().toString());
System.out.println("系统启动时间: " + new Date(os.getSystemBootTime() * 1000L));
System.out.println("运行时间: " + FormatUtil.formatElapsedSecs(os.getSystemUptime()));
System.out.println("进程数: " + os.getProcessCount());
System.out.println("线程数: " + os.getThreadCount());
System.out.println("位数: " + (os.getBitness() == 64 ? "64位" : "32位"));
}
private static void printComputerSystemInfo(ComputerSystem computerSystem) {
System.out.println("\n=== 计算机系统信息 ===");
System.out.println("制造商: " + computerSystem.getManufacturer());
System.out.println("型号: " + computerSystem.getModel());
System.out.println("序列号: " + computerSystem.getSerialNumber());
Firmware firmware = computerSystem.getFirmware();
System.out.println("\n固件信息:");
System.out.println(" 制造商: " + firmware.getManufacturer());
System.out.println(" 名称: " + firmware.getName());
System.out.println(" 描述: " + firmware.getDescription());
System.out.println(" 版本: " + firmware.getVersion());
System.out.println(" 发布日期: " + (firmware.getReleaseDate() == null ? "未知" : firmware.getReleaseDate()));
Baseboard baseboard = computerSystem.getBaseboard();
System.out.println("\n主板信息:");
System.out.println(" 制造商: " + baseboard.getManufacturer());
System.out.println(" 型号: " + baseboard.getModel());
System.out.println(" 版本: " + baseboard.getVersion());
System.out.println(" 序列号: " + baseboard.getSerialNumber());
}
private static void printCpuInfo(CentralProcessor processor) {
System.out.println("\n=== CPU信息 ===");
System.out.println("标识符: " + processor.getProcessorIdentifier().getIdentifier());
System.out.println("微架构: " + processor.getProcessorIdentifier().getMicroarchitecture());
System.out.println("供应商: " + processor.getProcessorIdentifier().getVendor());
System.out.println("系列: " + processor.getProcessorIdentifier().getFamily());
System.out.println("型号: " + processor.getProcessorIdentifier().getModel());
System.out.println("步进: " + processor.getProcessorIdentifier().getStepping());
System.out.println("物理核心数: " + processor.getPhysicalProcessorCount());
System.out.println("逻辑核心数: " + processor.getLogicalProcessorCount());
System.out.println("最大频率: " + FormatUtil.formatHertz(processor.getMaxFreq()));
// CPU负载
long[] prevTicks = processor.getSystemCpuLoadTicks();
Util.sleep(1000);
long[] ticks = processor.getSystemCpuLoadTicks();
long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
long sys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.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 totalCpu = user + nice + sys + idle + iowait + irq + softirq + steal;
System.out.println("\nCPU使用情况:");
System.out.println(" 用户态: " + formatPercent(user, totalCpu));
System.out.println(" 低优先级用户态: " + formatPercent(nice, totalCpu));
System.out.println(" 内核态: " + formatPercent(sys, totalCpu));
System.out.println(" 空闲: " + formatPercent(idle, totalCpu));
System.out.println(" IO等待: " + formatPercent(iowait, totalCpu));
System.out.println(" 硬件中断: " + formatPercent(irq, totalCpu));
System.out.println(" 软件中断: " + formatPercent(softirq, totalCpu));
System.out.println(" 虚拟化等待: " + formatPercent(steal, totalCpu));
System.out.println(" 总使用率: " + formatPercent(totalCpu - idle, totalCpu));
}
private static void printMemoryInfo(GlobalMemory memory) {
System.out.println("\n=== 内存信息 ===");
System.out.println("总内存: " + FormatUtil.formatBytes(memory.getTotal()));
System.out.println("可用内存: " + FormatUtil.formatBytes(memory.getAvailable()));
System.out.println("已用内存: " + FormatUtil.formatBytes(memory.getTotal() - memory.getAvailable()));
System.out.println("使用率: " + String.format("%.1f%%", (memory.getTotal() - memory.getAvailable()) / (double) memory.getTotal() * 100));
}
private static void printDiskInfo(List<HWDiskStore> diskStores) {
System.out.println("\n=== 磁盘信息 ===");
for (HWDiskStore disk : diskStores) {
System.out.println("\n磁盘: " + disk.getName());
System.out.println(" 型号: " + disk.getModel());
System.out.println(" 序列号: " + disk.getSerial());
System.out.println(" 大小: " + FormatUtil.formatBytes(disk.getSize()));
System.out.println(" 读取次数: " + disk.getReads());
System.out.println(" 写入次数: " + disk.getWrites());
System.out.println(" 读取字节: " + FormatUtil.formatBytes(disk.getReadBytes()));
System.out.println(" 写入字节: " + FormatUtil.formatBytes(disk.getWriteBytes()));
System.out.println(" 传输时间(ms): " + disk.getTransferTime());
List<HWPartition> partitions = disk.getPartitions();
if (partitions != null && !partitions.isEmpty()) {
System.out.println(" 分区信息:");
for (HWPartition part : partitions) {
System.out.println(" 分区: " + part.getIdentification());
System.out.println(" 名称: " + part.getName());
System.out.println(" 类型: " + part.getType());
System.out.println(" 挂载点: " + part.getMountPoint());
System.out.println(" 大小: " + FormatUtil.formatBytes(part.getSize()));
}
}
}
}
private static void printFileSystemInfo(List<OSFileStore> fileStores) {
System.out.println("\n=== 文件系统信息 ===");
for (OSFileStore fs : fileStores) {
System.out.println("\n文件系统: " + fs.getName());
System.out.println(" 挂载点: " + fs.getMount());
System.out.println(" 描述: " + fs.getDescription());
System.out.println(" 类型: " + fs.getType());
System.out.println(" 总空间: " + FormatUtil.formatBytes(fs.getTotalSpace()));
System.out.println(" 可用空间: " + FormatUtil.formatBytes(fs.getFreeSpace()));
System.out.println(" 已用空间: " + FormatUtil.formatBytes(fs.getTotalSpace() - fs.getFreeSpace()));
System.out.println(" 使用率: " + String.format("%.1f%%",
(fs.getTotalSpace() > 0 ? (double)(fs.getTotalSpace() - fs.getFreeSpace()) / fs.getTotalSpace() * 100 : 0)));
System.out.println(" 可读: " + (fs.getUsableSpace() > 0 ? "是" : "否"));
System.out.println(" 可写: " + (fs.getUsableSpace() > 0 ? "是" : "否"));
}
}
private static void printNetworkInfo(List<NetworkIF> networkIFs) {
System.out.println("\n=== 网络信息 ===");
for (NetworkIF net : networkIFs) {
System.out.println("\n网络接口: " + net.getName());
System.out.println(" 显示名称: " + net.getDisplayName());
System.out.println(" MAC地址: " + net.getMacaddr());
System.out.println(" IPv4地址: " + Arrays.toString(net.getIPv4addr()));
System.out.println(" IPv6地址: " + Arrays.toString(net.getIPv6addr()));
System.out.println(" MTU: " + net.getMTU());
System.out.println(" 速度: " + (net.getSpeed() > 0 ? FormatUtil.formatValue(net.getSpeed(), "bps") : "未知"));
// 获取网络流量统计
System.out.println("\n 网络统计:");
System.out.println(" 接收字节: " + FormatUtil.formatBytes(net.getBytesRecv()));
System.out.println(" 发送字节: " + FormatUtil.formatBytes(net.getBytesSent()));
System.out.println(" 接收包数: " + net.getPacketsRecv());
System.out.println(" 发送包数: " + net.getPacketsSent());
System.out.println(" 接收错误: " + net.getInErrors());
System.out.println(" 发送错误: " + net.getOutErrors());
// 计算网络速度
long[] prevRecv = {net.getBytesRecv()};
long[] prevSent = {net.getBytesSent()};
Util.sleep(1000);
net.updateAttributes();
System.out.println("\n 当前速度:");
System.out.println(" 接收速度: " + FormatUtil.formatBytes(net.getBytesRecv() - prevRecv[0]) + "/s");
System.out.println(" 发送速度: " + FormatUtil.formatBytes(net.getBytesSent() - prevSent[0]) + "/s");
}
}
private static void printGraphicsInfo(List<GraphicsCard> graphicsCards) {
System.out.println("\n=== 显卡信息 ===");
for (GraphicsCard card : graphicsCards) {
System.out.println("\n显卡: " + card.getName());
System.out.println(" 设备ID: " + card.getDeviceId());
System.out.println(" 供应商: " + card.getVendor());
System.out.println(" VRAM: " + FormatUtil.formatBytes(card.getVRam()));
System.out.println(" 版本: " + card.getVersionInfo());
}
}
private static void printSensorsInfo(Sensors sensors) {
System.out.println("\n=== 传感器信息 ===");
System.out.println("CPU温度: " + (sensors.getCpuTemperature() > 0 ?
String.format("%.1f°C", sensors.getCpuTemperature()) : "不可用"));
System.out.println("CPU电压: " + (sensors.getCpuVoltage() > 0 ?
String.format("%.2fV", sensors.getCpuVoltage()) : "不可用"));
int[] fanSpeeds = sensors.getFanSpeeds();
if (fanSpeeds.length > 0) {
System.out.println("风扇转速:");
for (int i = 0; i < fanSpeeds.length; i++) {
System.out.println(" 风扇" + (i + 1) + ": " + fanSpeeds[i] + " RPM");
}
} else {
System.out.println("风扇转速: 不可用");
}
}
private static void printPowerInfo(List<PowerSource> powerSources) {
System.out.println("\n=== 电源信息 ===");
if (powerSources.isEmpty()) {
System.out.println("没有检测到电源信息");
return;
}
for (PowerSource power : powerSources) {
System.out.println("\n电源: " + power.getName());
System.out.println(" 设备名称: " + power.getDeviceName());
System.out.println(" 是否交流供电: " + (power.isPowerOnLine() ? "是" : "否"));
System.out.println(" 是否正在充电: " + (power.isCharging() ? "是" : "否"));
System.out.println(" 是否放电中: " + (power.isDischarging() ? "是" : "否"));
System.out.println(" 当前容量: " + power.getCurrentCapacity() + " mWh");
System.out.println(" 最大容量: " + power.getMaxCapacity() + " mWh");
System.out.println(" 设计容量: " + power.getDesignCapacity() + " mWh");
System.out.println(" 循环计数: " + power.getCycleCount());
System.out.println(" 化学类型: " + power.getChemistry());
System.out.println(" 制造日期: " + power.getManufactureDate());
System.out.println(" 制造商: " + power.getManufacturer());
System.out.println(" 序列号: " + power.getSerialNumber());
System.out.println(" 温度: " + power.getTemperature() + "°C");
}
}
private static void printProcessInfo(List<OSProcess> processes) {
System.out.println("\n=== 进程信息 ===");
System.out.println("总进程数: " + processes.size());
}
private static String formatPercent(long portion, long total) {
return String.format("%.1f%%", total > 0 ? portion * 100d / total : 0);
}
}

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐
所有评论(0)