使用oshi获取系统信息。 最新版本 的兼容问题解决

直接绕过运维,后台查询系统硬件信息

pom.xml 增加oshi-core包

		<!-- 获取系统信息 -->
		<dependency>
			<groupId>com.github.oshi</groupId>
			<artifactId>oshi-core</artifactId>
			<version>3.9.1</version>
		</dependency>
package com.qh.common.controller;

import com.qh.platform.domain.Server;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 服务器监控
 * 
 * @author ruoyi
 */

@RequestMapping("/monitor/server")
@Controller
public class ServerController extends BaseController
{
    private String prefix = "common/server";

    @RequiresPermissions("monitor:server:list")
    @GetMapping()
    public String server(ModelMap mmap) throws Exception
    {
        Server server = new Server();
        server.copyTo();
        mmap.put("server", server);
        return prefix + "/server";
    }
}

新增工具类:Server

package com.qh.platform.domain;

import com.qh.common.utils.Arith;
import com.qh.common.utils.IPUtils;
import com.qh.platform.domain.server.*;
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.UnknownHostException;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

/**
 * 服务器相关信息
 * 
 */
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();
        hal.getProcessor();

        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[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.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.setComputerName(IPUtils.getHostName());
        sys.setComputerIp(IPUtils.getHostIp());
        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();
        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);
        }
    }
}

页面代码,本人用的前端框架是layuimini.js

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head th:include="include :: header"></head>
<body class="gray-bg">
    <div class="wrapper wrapper-content">
        <div class="col-sm-12">
            <div class="row">
                <div class="col-sm-6">
                    <div class="ibox float-e-margins">
                        <div class="ibox-title">
                            <h5>CPU</h5>
                            <div class="ibox-tools">
                                <a class="collapse-link"><i class="fa fa-chevron-up"></i>
                                </a>
                                <a class="close-link"><i class="fa fa-times"></i></a>
                            </div>
                        </div>
                        <div class="ibox-content">
                            <table class="table table-hover no-margins">
                                <thead>
                                    <tr>
                                        <th>属性</th>
                                        <th>值</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>核心数</td>
                                        <td th:text="${server.cpu.cpuNum}">0个</td>
                                    </tr>
                                    <tr>
                                        <td>用户使用率</td>
                                        <td th:text="${server.cpu.used + '%'}">0%</td>
                                    </tr>
                                    <tr>
                                        <td>系统使用率</td>
                                        <td th:text="${server.cpu.sys + '%'}">0%</td>
                                    </tr>
                                    <tr>
                                        <td>当前空闲率</td>
                                        <td th:text="${server.cpu.free + '%'}">0%</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <div class="col-sm-6">
                    <div class="ibox float-e-margins">
                        <div class="ibox-title">
                            <h5>内存</h5>
                            <div class="ibox-tools">
                                <a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
                                <a class="close-link"><i class="fa fa-times"></i></a>
                            </div>
                        </div>
                        <div class="ibox-content">
                            <table class="table table-hover no-margins">
                                <thead>
                                    <tr>
                                        <th>属性</th>
                                        <th>内存</th>
                                        <th>JVM</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>总内存</td>
                                        <td th:text="${server.mem.total + 'G'}">0GB</td>
                                        <td th:text="${server.jvm.total + 'M'}">0MB</td>
                                    </tr>
                                    <tr>
                                        <td>已用内存</td>
                                        <td th:text="${server.mem.used + 'G'}">0GB</td>
                                        <td th:text="${server.jvm.used + 'M'}">0MB</td>
                                    </tr>
                                    <tr>
                                        <td>剩余内存</td>
                                        <td th:text="${server.mem.free + 'G'}">0GB</td>
                                        <td th:text="${server.jvm.free + 'M'}">0MB</td>
                                    </tr>
                                    <tr>
                                        <td>使用率</td>
                                        <td th:class="${server.mem.usage gt 80} ? 'text-danger'">[[${server.mem.usage}]]%</td>
                                        <td th:class="${server.jvm.usage gt 80} ? 'text-danger'">[[${server.jvm.usage}]]%</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-sm-12">
                    <div class="ibox float-e-margins">
                        <div class="ibox-title">
                            <h5>服务器信息</h5>
                            <div class="ibox-tools">
                                <a class="collapse-link">
                                    <i class="fa fa-chevron-up"></i>
                                </a>
                                <a class="close-link">
                                    <i class="fa fa-times"></i>
                                </a>
                            </div>
                        </div>
                        <div class="ibox-content">
                            <div class="row">
                                <div class="col-sm-12">
                                    <table class="table table-hover margin bottom">
                                        <tbody>
                                            <tr>
                                                <td>服务器名称</td>
                                                <td th:text="${server.sys.computerName}">RuoYi</td>
                                                <td>操作系统</td>
                                                <td th:text="${server.sys.osName}">Linux</td>
                                            </tr>
                                            <tr>
                                                <td>服务器IP</td>
                                                <td th:text="${server.sys.computerIp}">127.0.0.1</td>
                                                <td>系统架构</td>
                                                <td th:text="${server.sys.osArch}">amd64</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-sm-12">
                    <div class="ibox float-e-margins">
                        <div class="ibox-title">
                            <h5>Java虚拟机信息</h5>
                            <div class="ibox-tools">
                                <a class="collapse-link">
                                    <i class="fa fa-chevron-up"></i>
                                </a>
                                <a class="close-link">
                                    <i class="fa fa-times"></i>
                                </a>
                            </div>
                        </div>
                        <div class="ibox-content">

                            <div class="row">
                                <div class="col-sm-12">
                                    <table class="table table-hover margin bottom">
                                        <tbody>
                                            <tr>
                                                <td>Java名称</td>
                                                <td th:text="${server.jvm.name}">Java</td>
                                                <td>Java版本</td>
                                                <td th:text="${server.jvm.version}">1.8.0</td>
                                            </tr>
                                            <tr>
                                                <td>启动时间</td>
                                                <td th:text="${server.jvm.startTime}">2018-12-31 00:00:00</td>
                                                <td>运行时长</td>
                                                <td th:text="${server.jvm.runTime}">0天0时0分0秒</td>
                                            </tr>
                                            <tr>
                                                <td colspan="1">安装路径</td>
                                                <td colspan="3" th:text="${server.jvm.home}"></td>
                                            </tr>
                                             <tr>
                                                <td colspan="1">项目路径</td>
                                                <td colspan="3" th:text="${server.sys.userDir}"></td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-sm-12">
                    <div class="ibox float-e-margins">
                        <div class="ibox-title">
                            <h5>磁盘状态</h5>
                            <div class="ibox-tools">
                                <a class="collapse-link">
                                    <i class="fa fa-chevron-up"></i>
                                </a>
                                <a class="close-link">
                                    <i class="fa fa-times"></i>
                                </a>
                            </div>
                        </div>
                        <div class="ibox-content">

                            <div class="row">
                                <div class="col-sm-12">
                                    <table class="table table-hover margin bottom">
                                        <thead>
                                            <tr>
                                                <th>盘符路径</th>
                                                <th>文件系统</th>
                                                <th>盘符类型</th>
                                                <th>总大小</th>
                                                <th>可用大小</th>
                                                <th>已用大小</th>
                                                <th>已用百分比</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr th:each="sysFile : ${server.sysFiles}">
                                                <td th:text="${sysFile.dirName}">C:\</td>
                                                <td th:text="${sysFile.sysTypeName}">NTFS</td>
                                                <td th:text="${sysFile.typeName}">local</td>
                                                <td th:text="${sysFile.total}">0GB</td>
                                                <td th:text="${sysFile.free}">0GB</td>
                                                <td th:text="${sysFile.used}">0GB</td>
                                                <td th:class="${sysFile.usage gt 80} ? 'text-danger'">[[${sysFile.usage}]]%</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<div th:include="include :: footer"></div>
<script>
    $(".modal").appendTo("body"), $("[data-toggle=popover]").popover(), $(".collapse-link").click(function() {
        var div_ibox = $(this).closest("div.ibox"),
        e = $(this).find("i"),
        i = div_ibox.find("div.ibox-content");
        i.slideToggle(200),
        e.toggleClass("fa-chevron-up").toggleClass("fa-chevron-down"),
        div_ibox.toggleClass("").toggleClass("border-bottom"),
        setTimeout(function() {
        	div_ibox.resize();
        }, 50);
    }), $(".close-link").click(function () {
		var div_ibox = $(this).closest("div.ibox");
		div_ibox.remove()
	});
</script>
</html>

现在来看看显示效果:(本人电脑配置信息就出来了,怎么样是不是配置很强大。做为高级搬砖的,电脑不能怂)

拓展一下:  这 oshi-core 用的版本会比较低 3.9   那么我们根据maven上面版本升级一下

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

这时候就会报错了:

Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: com/sun/jna/platform/win32/VersionHelpers 

根据报错查询问题,一般情况就是项目的jar 版本不一致。然后根据提示的jna/platform这个去找下最新的包。

<dependency>
			<groupId>net.java.dev.jna</groupId>
			<artifactId>jna-platform</artifactId>
			<version>5.5.0</version>
		</dependency>

加了这个包之后 报错信息就不一样了:

Caused by: java.lang.AbstractMethodError: Receiver class com.sun.jna.platform.win32.WinNT$OSVERSIONINFOEX does not define or inherit an implementation of the resolved method abstract getFieldOrder()Ljava/util/List; of abstract class com.sun.jna.Structure.

这个错就更明显   包版本的问题,还是少了一个包。后面找了很多资料  看了一些源码发现这个.jna.platform还有一个包

<dependency>
			<groupId>net.java.dev.jna</groupId>
			<artifactId>jna</artifactId>
			<version>5.5.0</version>
		</dependency>

现在就可以了 :

最后完整的如下: 因为我自己升级这个版本,网上基本找不到解决办法。自己研究了好一会。记录一下。正常项目不会在后台加这种。服务器的监控也都是运维去做。这个做出来只是针对小公司使用。

<!-- 获取系统信息 -->
		<dependency>
			<groupId>com.github.oshi</groupId>
			<artifactId>oshi-core</artifactId>
			<version>4.4.0</version>
		</dependency>
		<dependency>
			<groupId>net.java.dev.jna</groupId>
			<artifactId>jna-platform</artifactId>
			<version>5.5.0</version>
		</dependency>
		<dependency>
			<groupId>net.java.dev.jna</groupId>
			<artifactId>jna</artifactId>
			<version>5.5.0</version>
		</dependency>
发布了35 篇原创文章 · 获赞 1 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/u010494101/article/details/104362887