Java 使用 oshi 获取当前服务硬件信息(操作系统、CPU、内存、磁盘)

一、导包

这里需要引入两个依赖包:

<dependency>
	<groupId>com.github.oshigroupId>
	<artifactId>oshi-coreartifactId>
	<version>6.3.0version>
dependency>
<dependency>
    <groupId>org.projectlombokgroupId>
    <artifactId>lombokartifactId>
    <version>1.18.24version>
dependency>

二、工具类

HardWareUtil:

import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;
import oshi.util.Util;
import src.com.dxc.enumerate.SizeEnum;
import src.com.dxc.model.*;
import oshi.hardware.CentralProcessor.TickType;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Properties;

/**
 * 硬件信息工具类
 *
 * @Author xincheng.du
 * @Date 2023/7/6 17:17
 */
public class HardWareUtil {

    private HardWareUtil() {}

    /**
     * 等待休眠时间,单位ms
     */
    private static final int WAIT_TIME_MS = 1000;

    /**
     * 获取cpu信息
     *
     * @return  cpu信息
     */
    public static CpuInfo getCpuInfo() {
        oshi.SystemInfo si = new oshi.SystemInfo();
        CentralProcessor processor = si.getHardware().getProcessor();
        // CPU信息
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        Util.sleep(WAIT_TIME_MS);
        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;
        CpuInfo cpuInfo = new CpuInfo();
        cpuInfo.setCpuNum(processor.getLogicalProcessorCount());
        cpuInfo.setTotal(totalCpu);
        cpuInfo.setSys(cSys);
        cpuInfo.setUsed(user);
        cpuInfo.setWait(ioWait);
        cpuInfo.setFree(idle);
        return cpuInfo;
    }

    /**
     * 获取内存信息
     *
     * @param size  大小单位,默认为B
     * @return      内存信息
     */
    public static MemoryInfo getMemoryInfo(SizeEnum size) {
        SystemInfo si = new SystemInfo();
        GlobalMemory memory = si.getHardware().getMemory();
        // 内存信息
        MemoryInfo mem = new MemoryInfo();
        mem.setTotal(Objects.isNull(size) ? memory.getTotal() : (float) memory.getTotal() / size.getSize());
        mem.setUsed(Objects.isNull(size) ? (memory.getTotal() - memory.getAvailable()) : (float) (memory.getTotal() - memory.getAvailable()) / size.getSize());
        mem.setFree(Objects.isNull(size) ? memory.getAvailable() : (float) memory.getAvailable() / size.getSize());
        return mem;
    }

    /**
     * 获取服务器信息
     *
     * @return  服务器信息
     */
    public static SystemDetails getSystemInfo() {
        // 服务器信息
        SystemDetails details = new SystemDetails();
        Properties props = System.getProperties();
        details.setComputerName(IpUtils.getHostName());
        details.setComputerIp(IpUtils.getHostIp());
        details.setOsName(props.getProperty("os.name"));
        details.setOsArch(props.getProperty("os.arch"));
        details.setUserDir(props.getProperty("user.dir"));
        return details;
    }

    /**
     * 获取Java虚拟机信息
     */
    public static JvmInfo getJvmInfo() {
        JvmInfo jvmInfo = new JvmInfo();
        Properties props = System.getProperties();
        jvmInfo.setTotal(Runtime.getRuntime().totalMemory());
        jvmInfo.setMax(Runtime.getRuntime().maxMemory());
        jvmInfo.setFree(Runtime.getRuntime().freeMemory());
        jvmInfo.setVersion(props.getProperty("java.version"));
        jvmInfo.setHome(props.getProperty("java.home"));
        return jvmInfo;
    }

    /**
     * 获取磁盘信息
     */
    public static List<SysFile> getSysFiles() {
        SystemInfo si = new SystemInfo();
        // 获取操作系统
        OperatingSystem operatingSystem = si.getOperatingSystem();
        // 获取操作系统的文件系统
        FileSystem fileSystem = operatingSystem.getFileSystem();
        // 获取文件存储信息
        List<OSFileStore> fsArray = fileSystem.getFileStores();
        List<SysFile> sysFiles = new ArrayList<>();
        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(mul(div(used, total, 4), 100));
            sysFiles.add(sysFile);
        }
        return sysFiles;
    }

    /**
     * 字节转换
     *
     * @param size 字节大小
     * @return 转换后值
     */
    public static String convertFileSize(long size) {
        if (size >= SizeEnum.GB.getSize()) {
            return String.format("%.1f GB", (float) size / SizeEnum.GB.getSize());
        } else if (size >= SizeEnum.MB.getSize()) {
            float f = (float) size / SizeEnum.MB.getSize();
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } else if (size >= SizeEnum.KB.getSize()) {
            float f = (float) size / SizeEnum.KB.getSize();
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        } else {
            return String.format("%d B", size);
        }
    }

    /**
     * 提供精确的乘法运算。
     * @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();
    }

    /**
     * 提供(相对)精确的除法运算。当发生除不尽的情况时,由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();
    }
}

CpuInfo:

import lombok.Data;

/**
 * CPU相关信息
 * 
 * @Author xincheng.du
 * @Date 2023/7/6 17:17
 */
@Data
public class CpuInfo {
    /**
     * 核心数
     */
    private int cpuNum;

    /**
     * CPU总的使用率
     */
    private double total;

    /**
     * CPU系统使用率
     */
    private double sys;

    /**
     * CPU用户使用率
     */
    private double used;

    /**
     * CPU当前等待率
     */
    private double wait;

    /**
     * CPU当前空闲率
     */
    private double free;

}

JvmInfo:

import lombok.Data;

/**
 * JVM相关信息
 * 
 * @Author xincheng.du
 * @Date 2023/7/6 17:17
 */
@Data
public class JvmInfo
{
    /**
     * 当前JVM占用的内存总数(M)
     */
    private double total;

    /**
     * JVM最大可用内存总数(M)
     */
    private double max;

    /**
     * JVM空闲内存(M)
     */
    private double free;

    /**
     * JDK版本
     */
    private String version;

    /**
     * JDK路径
     */
    private String home;
    
}

MemoryInfo:

import lombok.Data;

/**
 * 內存相关信息
 * 
 * @Author xincheng.du
 * @Date 2023/7/6 17:17
 */
@Data
public class MemoryInfo {
    /**
     * 内存总量
     */
    private double total;

    /**
     * 已用内存
     */
    private double used;

    /**
     * 剩余内存
     */
    private double free;

}

SysFile:

/**
 * 系统文件相关信息
 * 
 * @Author xincheng.du
 * @Date 2023/7/6 17:17
 */
@Data
public class SysFile
{
    /**
     * 盘符路径
     */
    private String dirName;

    /**
     * 盘符类型
     */
    private String sysTypeName;

    /**
     * 文件类型
     */
    private String typeName;

    /**
     * 总大小
     */
    private String total;

    /**
     * 剩余大小
     */
    private String free;

    /**
     * 已经使用量
     */
    private String used;

    /**
     * 资源的使用率
     */
    private double usage;

}

SystemDetails:

import lombok.Data;

/**
 * 系统相关信息
 * 
 * @Author xincheng.du
 * @Date 2023/7/6 17:17
 */
@Data
public class SystemDetails {
    /**
     * 服务器名称
     */
    private String computerName;

    /**
     * 服务器Ip
     */
    private String computerIp;

    /**
     * 项目路径
     */
    private String userDir;

    /**
     * 操作系统
     */
    private String osName;

    /**
     * 系统架构
     */
    private String osArch;
    
}

SizeEnum:

import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * 大小枚举
 *
 * @Author xincheng.du
 * @Date 2023/7/6 11:42
 */
@AllArgsConstructor
public enum SizeEnum {

    /**
     * 1KB = 1024B
     */
    KB(1024),

    /**
     * 1MB = 1024KB
     */
    MB(KB.size * 1024),

    /**
     * 1GB = 1024MB
     */
    GB(MB.size * 1024);

    /**
     * 1(K/M/G)B = ? B
     */
    @Getter
    private final long size;
}

三、测试

public static void main(String[] args) {
        CpuInfo cpuInfo = HardWareUtil.getCpuInfo();
        JvmInfo jvmInfo = HardWareUtil.getJvmInfo();
        SystemDetails systemInfo = HardWareUtil.getSystemInfo();
        MemoryInfo memoryInfo = HardWareUtil.getMemoryInfo(SizeEnum.GB);
        List<SysFile> sysFiles = HardWareUtil.getSysFiles();
        System.out.println(cpuInfo);
        System.out.println(jvmInfo);
        System.out.println(systemInfo);
        System.out.println(memoryInfo);
        System.out.println(sysFiles);
    }

控制台输出:

CpuInfo(cpuNum=16, total=16501.0, sys=329.0, used=657.0, wait=0.0, free=15419.0)
JvmInfo(total=2.64241152E8, max=4.211081216E9, free=2.5297664E8, version=11.0.18, home=C:\Program Files\Java\jdk-11)
SystemDetails(computerName=DESKTOP-HPOJ5DN, computerIp=192.168.110.202, userDir=E:\JavaWorkspace\oshi_study, osName=Windows 10, osArch=amd64)
MemoryInfo(total=15.683177947998047, used=11.597965240478516, free=4.085212707519531)
[SysFile(dirName=C:, sysTypeName=NTFS, typeName=本地固定磁盘 (C:), total=250.0 GB, free=159.6 GB, used=90.4 GB, usage=36.17), SysFile(dirName=D:, sysTypeName=NTFS, typeName=本地固定磁盘 (D:), total=224.7 GB, free=219.0 GB, used=5.8 GB, usage=2.56), SysFile(dirName=E:, sysTypeName=NTFS, typeName=本地固定磁盘 (E:), total=476.9 GB, free=435.4 GB, used=41.5 GB, usage=8.71)]

注:本文部分代码参考自开源框架若依,官网地址:http://www.ruoyi.vip/,官方文档地址:http://doc.ruoyi.vip/

你可能感兴趣的:(java,oshi,服务器信息)