获取系统信息(oshi-core)

1.导入maven

<dependency>
    <groupId>com.github.oshi</groupId>
    <artifactId>oshi-core</artifactId>
    <version>4.5.2</version>
</dependency>

 2.API

对象 方法 描述
SystemInfo getOperatingSystem() 获取操作系统信息,OperatingSystem
getHardware() 获取硬件信息,HardwareAbstractionLayer
OperatingSystem getFamily() 获取操作系统名称,例如 Windows
getManufacturer() 获取供货商,例如 Microsoft
getVersion() 获取操作系统版本信息
getFileSystem() 获取系统硬盘信息,FileSystem
getProcesses(int pId, OperatingSystem.ProcessSort var2) 通过 进程id 获取进程信息,并设置排序方式,OSProcess[]
getProcess(int pId) 通过 进程id 获取一个进程信息,OSProcess
getProcesses(Collection<Integer> pId) 获取多个进程信息,List<OSProcess>
getChildProcesses(int var1, int var2, OperatingSystem.ProcessSort var3) 获取子进程,OSProcess[]
getProcessId() 获取进程id
getProcessCount() 获取进程数量
getThreadCount() 获取网络相关参数,NetworkParams
HardwareAbstractionLayer getComputerSystem() 获取计算机系统信息,ComputerSystem
getProcessor() 获取处理器信息,CentralProcessor
getMemory() 获取内存信息,GlobalMemory
getPowerSources() 获取电源信息,PowerSource
getDiskStores() 获取硬件磁盘信息,HWDiskStore
getNetworkIFs() 获取网络信息,NetworkIF
getDisplays() 获取显示信息,Display
getSensors() 获取传感器信息,Sensors
getUsbDevices(boolean var1) 获取USB设备信息,UsbDevice
OperatingSystemVersion getBuildNumber() 获取内部编号
getCodeName() 代码名称
getVersion() 获取版本
FileSystem getMaxFileDescriptors() 获取最大文件描述符
getOpenFileDescriptors() 获取打开文件描述符
getFileStores() 获取盘符相关信息
OSProcess getName() 进程程序名称
getPath()     进程程序所在位置
getCommandLine()     获取命令行
getCurrentWorkingDirectory()     获取当前工作目录
getUser()     获取用户信息
getUserID()     获取用户id
getGroup()     获取组信息
getGroupID()     获取组id
getState()     状态
getProcessID()     获取进程id
getParentProcessID()   获取父进程id
getThreadCount()     获取线程数
getPriority()     优先级
getVirtualSize()     虚拟大小
getResidentSetSize()     实际使用物理内存
getKernelTime()     内核时间
getUserTime()     用户时间
getUpTime()     正常运行时间
getStartTime()     开始时间
getBytesRead()     读取字节
getBytesWritten()     写入字节
getOpenFiles()     打开文件数量
NetworkParams getDnsServers()   获取域名地址
getHostName()     获取主机名
getDomainName()   获取域名
getIpv4DefaultGateway()     获取默认Ipv4
getIpv6DefaultGateway()     获取默认Ipv6
OSFileStore getName()     磁盘名称
getVolume()          文件集  
getLogicalVolume()     合理的文件集
getMount()     盘符
getDescription()     描述
getType()     类型
getUUID()   磁盘UUID
getUsableSpace()     可用空间
getTotalSpace()     总空间
ComputerSystem   getManufacturer()     获取制造商
getModel()     获取型号
getSerialNumber()     获取序列号
getFirmware()     获取固件信息,Firmware
getBaseboard()     获取外壳信息,Baseboard
Firmware getManufacturer()     获取制造商信息
getName()     获取名称
getDescription()     获取描述信息
getVersion()     获取版本
getReleaseDate()     获取发布时间
Baseboard getManufacturer() 获取制造商信息
getModel()     获取型号
getVersion()     获取版本信息
getSerialNumber()   获取序列号
CentralProcessor  getVendor()     获取供应商
getName()     获取cpu名称
getVendorFreq()     获取供应商频率
getProcessorID()     获取处理器id
getIdentifier()     获取标识符
isCpu64bit()     判断cpu是否为64位的
getStepping()     获取cpu步进
getModel()   获取型号
getFamily()     获取家族
getSystemCpuLoadBetweenTicks()   获取cpu负载间隔刻度
getSystemCpuLoadTicks()   获取cpu负载刻度
getSystemCpuLoad()   获取cpu负载
getSystemLoadAverage()     获取cpu平均负载
getSystemLoadAverage(int var1)   获取cpu平均负载
getProcessorCpuLoadBetweenTicks()  获取处理器cpu负载间隔刻度
getProcessorCpuLoadTicks()     获取处理器cpu负载刻度
getSystemUptime()     获取正常运行时间
getLogicalProcessorCount()     获取逻辑处理器数量
getPhysicalProcessorCount()     获取物理处理器数量
getPhysicalPackageCount()     获取物理包装数量
getContextSwitches()     获取上下文切换数量
getInterrupts()     获取中断
GlobalMemory getTotal()     获取总内存
getAvailable()     获取可用系统运行内存
getSwapTotal()     获取可用虚拟总内存
getSwapUsed()     获取已用虚拟总内存
PowerSource getName()     获取名称
getRemainingCapacity()     获取剩余容量
getTimeRemaining()     获取剩余时间
HWDiskStore getName()     获取名称
getModel()     获取型号
getSerial()     获取序列号
getSize()     获取大小
getReads()     (读长)是高通量测序中一个反应获得的测序序列
getReadBytes()     读取字节
getWrites()     写长
getWriteBytes()     写入字节
getTransferTime()   获取转移时间
getPartitions()     获取分区,HWPartition
getTimeStamp()   获取时间戳
NetworkIF getName()     获取名称
getDisplayName()     获取显示名称
getMTU()     获取最大传输单元
getMacaddr()     获取MAC地址
getIPv4addr()     获取IPv4
getIPv6addr()     获取IPv6
getBytesRecv()     获取接收字节数
getBytesSent()     获取发送字节数
getPacketsRecv()   获取接收数据包
getPacketsSent()     获取发送数据包
getInErrors()     是否可达,正常 0
getOutErrors()     响应错误,无错误 0
getSpeed()     获取速率
getTimeStamp()     获取时间戳
Display getEdid()     中文名称扩展显示器识别数据
Sensors getCpuTemperature()    获取CPU温度
getFanSpeeds()     获取风扇速度
getCpuVoltage()     获取CPU电压
UsbDevice getName()     获取名称
getVendor()     获取供应商
getVendorId()     获取供应商id
getProductId()     获取商品id
getSerialNumber()     获取序列号
getConnectedDevices()     获取连接设备

示例:

工具类:

package com.zwq.utils;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;
import oshi.util.Util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.util.Properties;

public class SystemInfoUtils {
    private static final int OSHI_WAIT_SECOND = 1000;
    private static SystemInfo systemInfo = new SystemInfo();
    private static HardwareAbstractionLayer hardware = systemInfo.getHardware();
    private static OperatingSystem operatingSystem = systemInfo.getOperatingSystem();
    //CPU信息
    public static JSONObject getCpuInfo() {
        JSONObject cpuInfo = new JSONObject();
        CentralProcessor processor = hardware.getProcessor();
        // CPU信息
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        Util.sleep(OSHI_WAIT_SECOND);
        long[] ticks = processor.getSystemCpuLoadTicks();
        long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.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 cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
        long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
        long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
        long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
        //cpu核数
        cpuInfo.put("cpu核数", processor.getLogicalProcessorCount());
        //cpu系统使用率
        cpuInfo.put("cpu系统使用率", new DecimalFormat("#.##%").format(cSys * 1.0 / totalCpu));
        //cpu用户使用率
        cpuInfo.put("cpu用户使用率", new DecimalFormat("#.##%").format(user * 1.0 / totalCpu));
        //cpu当前等待率
        cpuInfo.put("cpu当前等待率", new DecimalFormat("#.##%").format(iowait * 1.0 / totalCpu));
        //cpu当前使用率
        cpuInfo.put("cpu当前使用率", new DecimalFormat("#.##%").format(1.0 - (idle * 1.0 / totalCpu)));
        System.out.println("CPU信息 = " + cpuInfo);
        return cpuInfo;
    }

    /**
     * 系统jvm信息
     */
    public static JSONObject getJvmInfo() {
        JSONObject cpuInfo = new JSONObject();
        Properties props = System.getProperties();
        Runtime runtime = Runtime.getRuntime();
        long jvmTotalMemoryByte = runtime.totalMemory();
        long freeMemoryByte = runtime.freeMemory();
        //jvm总内存
        cpuInfo.put("jvm总内存", formatByte(runtime.totalMemory()));
        //空闲空间
        cpuInfo.put("空闲空间", formatByte(runtime.freeMemory()));
        //jvm最大可申请
        cpuInfo.put("jvm最大可申请", formatByte(runtime.maxMemory()));
        //vm已使用内存
        cpuInfo.put("vm已使用内存", formatByte(jvmTotalMemoryByte - freeMemoryByte));
        //jvm内存使用率
        cpuInfo.put("jvm内存使用率", new DecimalFormat("#.##%").format((jvmTotalMemoryByte - freeMemoryByte) * 1.0 / jvmTotalMemoryByte));
        //jdk版本
        cpuInfo.put("jdk版本", props.getProperty("java.version"));
        //jdk路径
        cpuInfo.put("jdk路径", props.getProperty("java.home"));
        System.out.println("系统jvm信息 = " + cpuInfo);
        return cpuInfo;
    }

    /**
     * 系统内存信息
     */
    public static JSONObject getMemInfo() {
        JSONObject cpuInfo = new JSONObject();
        GlobalMemory memory = systemInfo.getHardware().getMemory();
        //总内存
        long totalByte = memory.getTotal();
        //剩余
        long acaliableByte = memory.getAvailable();
        //总内存
        cpuInfo.put("总内存", formatByte(totalByte));
        //使用
        cpuInfo.put("使用", formatByte(totalByte - acaliableByte));
        //剩余内存
        cpuInfo.put("剩余内存", formatByte(acaliableByte));
        //使用率
        cpuInfo.put("使用率", new DecimalFormat("#.##%").format((totalByte - acaliableByte) * 1.0 / totalByte));
        System.out.println("系统内存信息 = " + cpuInfo);
        return cpuInfo;
    }

    /**
     * 系统盘符信息
     */
    public static JSONArray getSysFileInfo() {
        JSONObject cpuInfo;
        JSONArray sysFiles = new JSONArray();
        FileSystem fileSystem = operatingSystem.getFileSystem();
        OSFileStore[] fsArray = fileSystem.getFileStores();
        for (OSFileStore fs : fsArray) {
            cpuInfo = new JSONObject();
            //盘符路径
            cpuInfo.put("盘符路径", fs.getMount());
            //盘符类型
            cpuInfo.put("盘符类型", fs.getType());
            //文件类型
            cpuInfo.put("文件类型", fs.getName());
            //总大小
            cpuInfo.put("总大小", formatByte(fs.getTotalSpace()));
            //剩余大小
            cpuInfo.put("剩余大小", formatByte(fs.getUsableSpace()));
            //已经使用量
            cpuInfo.put("已经使用量", formatByte(fs.getTotalSpace() - fs.getUsableSpace()));
            if (fs.getTotalSpace() == 0) {
                //资源的使用率
                cpuInfo.put("资源的使用率", 0);
            } else {
                cpuInfo.put("资源的使用率",new DecimalFormat("#.##%").format((fs.getTotalSpace() - fs.getUsableSpace()) * 1.0 / fs.getTotalSpace()));
            }
            sysFiles.add(cpuInfo);
        }
        System.out.println("系统盘符信息 = " + sysFiles);
        return sysFiles;
    }

    /**
     * 系统信息
     */
    public static JSONObject getSysInfo() throws UnknownHostException {
        JSONObject cpuInfo = new JSONObject();
        Properties props = System.getProperties();
        //操作系统名
        cpuInfo.put("操作系统名", props.getProperty("os.name"));
        //系统架构
        cpuInfo.put("系统架构", props.getProperty("os.arch"));
        //服务器名称
        cpuInfo.put("服务器名称", InetAddress.getLocalHost().getHostName());
        //服务器Ip
        cpuInfo.put("服务器Ip", InetAddress.getLocalHost().getHostAddress());
        //项目路径
        cpuInfo.put("项目路径", props.getProperty("user.dir"));
        System.out.println("系统信息 = " + cpuInfo);
        return cpuInfo;
    }

    /**
     * 所有系统信息
     */
    public static JSONObject getInfo() throws UnknownHostException {
        JSONObject info = new JSONObject();
        info.put("CPU信息", getCpuInfo());
        info.put("系统jvm信息", getJvmInfo());
        info.put("系统内存信息", getMemInfo());
        info.put("系统信息", getSysInfo());
        info.put("系统盘符信息", getSysFileInfo());
        return info;
    }

    /**
     * 单位转换
     */
    private static String formatByte(long byteNumber) {
        //换算单位
        double FORMAT = 1024.0;
        double kbNumber = byteNumber / FORMAT;
        if (kbNumber < FORMAT) {
            return new DecimalFormat("#.##KB").format(kbNumber);
        }
        double mbNumber = kbNumber / FORMAT;
        if (mbNumber < FORMAT) {
            return new DecimalFormat("#.##MB").format(mbNumber);
        }
        double gbNumber = mbNumber / FORMAT;
        if (gbNumber < FORMAT) {
            return new DecimalFormat("#.##GB").format(gbNumber);
        }
        double tbNumber = gbNumber / FORMAT;
        return new DecimalFormat("#.##TB").format(tbNumber);
    }
}

Msg:

package com.zwq.utils;

import java.util.HashMap;
import java.util.Map;

public class Msg {

    //自定义状态码
    private int code;

    //成功或失败 的提示信息
    private String msg;


    //用户要返回给浏览器的数据
    private Map<String, Object> content = new HashMap<String, Object>();

    //成功调用的方法---此处暂定 200为成功
    public static Msg success() {
        Msg msg = new Msg();
        msg.setCode(200);
        msg.setMsg("成功!");
        return msg;
    }

    //失败调用的方法---此处暂定 500为失败
    public static Msg fail() {
        Msg msg = new Msg();
        msg.setCode(500);
        msg.setMsg("失败!");
        return msg;
    }

    //添加数据
    public Msg add(String key, Object value) {
        this.getContent().put(key, value);
        return this;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Map<String, Object> getContent() {
        return content;
    }

    public void setContent(Map<String, Object> content) {
        this.content = content;
    }


}

controller:

@RestController
public class ServerController {
    @GetMapping("/server")
    @ApiOperation(value = "获取系统信息")
    public Msg server() throws UnknownHostException {
      return Msg.success().add("server", SystemInfoUtils.getInfo());
    }
}

猜你喜欢

转载自blog.csdn.net/m0_61157117/article/details/124689320