文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

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

2023-10-26 06:54

关注

一、导包

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

<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;public class HardWareUtil {    private HardWareUtil() {}        private static final int WAIT_TIME_MS = 1000;        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;    }        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;    }        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;    }        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;    }        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);        }    }        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();    }        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;@Datapublic class CpuInfo {        private int cpuNum;        private double total;        private double sys;        private double used;        private double wait;        private double free;}

JvmInfo:

import lombok.Data;@Datapublic class JvmInfo{        private double total;        private double max;        private double free;        private String version;        private String home;    }

MemoryInfo:

import lombok.Data;@Datapublic class MemoryInfo {        private double total;        private double used;        private double free;}

SysFile:

@Datapublic 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;@Datapublic class SystemDetails {        private String computerName;        private String computerIp;        private String userDir;        private String osName;        private String osArch;    }

SizeEnum:

import lombok.AllArgsConstructor;import lombok.Getter;@AllArgsConstructorpublic enum SizeEnum {        KB(1024),        MB(KB.size * 1024),        GB(MB.size * 1024);        @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/

来源地址:https://blog.csdn.net/weixin_44248000/article/details/131378993

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-人工智能
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯