使用oshi-core开发服务监控模块

如果文章对你有帮助欢迎【关注❤️❤️❤️点赞👍👍👍收藏⭐⭐⭐】一键三连!一起努力!

一、oshi-core简介

oshi-core组件是开源的获取系统信息的工具,通过该工具可以方便的帮助我们获取丰富的系统信息,包括:操作系统信息、服务器信息、JVM信息、磁盘信息等等。

今天我们就使用这个组件完成服务监控模块的开发,丰富我们的系统功能。

二、服务监控模块

实现后的样式:

在这里插入图片描述

1、引入依赖
  <!-- 获取系统信息 -->
   <dependency>
       <groupId>com.github.oshi</groupId>
       <artifactId>oshi-core</artifactId>
       <version>6.1.6</version>
   </dependency>
2、编写实体类和具体实现
/**
 * @description: 服务器相关信息
 * @author: Xiong
 * @date: 2022/12/8 10:26
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
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<>();

    public void setValueTo() {
        SystemInfo systemInfo = new SystemInfo();
        HardwareAbstractionLayer hal = systemInfo.getHardware();
        // cup信息
        setCpuInfo(hal.getProcessor());
        // 内存信息
        setMemInfo(hal.getMemory());
        // 服务器信息
        setSysInfo();
        // JVM信息
        setJvmInfo();
        // 磁盘信息
        setSysFiles(systemInfo.getOperatingSystem());
    }

    /**
     * 设置CPU信息
     */
    private void setCpuInfo(CentralProcessor processor) {
        // CPU信息
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        Util.sleep(OSHI_WAIT_SECOND);
        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 cSys = 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 + 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() {
        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);
        }
    }
}

3、Controller
/**
 * @description: 服务监控
 * @author: Xiong
 * @date: 2022/12/8 10:09
 */
@RestController
@RequestMapping("/server")
public class ServerController {

    @GetMapping("/")
    @ApiOperation(value = "获取服务器相关信息")
    public ResultData getServer() {
        Server server = new Server();
        server.setValueTo();
        return ResultData.success(server);
    }
}
4、Vue页面
<template>
  <div>
    <el-row>
      <el-col :span="12" style="padding-right: 15px; padding-left: 15px; margin-bottom: 10px;">
        <el-card>
          <div slot="header" class="el-icon-cpu"><b> CPU</b></div>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <table cellspacing="0" style="width: 100%;">
              <thead>
                <tr>
                  <th class="el-table__cell is-leaf"><div class="cell">属 性</div></th>
                  <th class="el-table__cell is-leaf"><div class="cell"></div></th>
                </tr>
              </thead>
              <tbody>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">核心数</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" v-if="server.cpu">{{ server.cpu.cpuNum }}</div></td>
              </tr>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">用户使用率</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" v-if="server.cpu">{{ server.cpu.used }} %</div></td>
              </tr>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">系统使用率</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" v-if="server.cpu">{{ server.cpu.sys }} %</div></td>
              </tr>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">当前空闲率</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" :class="{'text-success': server.cpu.free > 70}" v-if="server.cpu">{{ server.cpu.free }} %</div></td>
              </tr>
              </tbody>
            </table>
          </div>
        </el-card>
      </el-col>

      <el-col :span="12" style="padding-right: 15px; padding-left: 15px; margin-bottom: 10px;">
        <el-card>
          <div slot="header" class="el-icon-folder"><b> 内存</b></div>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <table cellspacing="0" style="width: 100%;">
              <thead>
              <tr>
                <th class="el-table__cell is-leaf"><div class="cell">属 性</div></th>
                <th class="el-table__cell is-leaf"><div class="cell">内 存</div></th>
                <th class="el-table__cell is-leaf"><div class="cell">JVM</div></th>
              </tr>
              </thead>
              <tbody>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">总内存</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" v-if="server.mem">{{ server.mem.total }} G</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" v-if="server.jvm">{{ server.jvm.total }} M</div></td>
              </tr>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">已用内存</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" v-if="server.mem">{{ server.mem.used }} G</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" v-if="server.jvm">{{ server.jvm.used }} M</div></td>
              </tr>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">剩余内存</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" v-if="server.mem">{{ server.mem.free }} G</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" v-if="server.jvm">{{ server.jvm.free }} M</div></td>
              </tr>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">使用率</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" v-if="server.mem" :class="{'text-danger': server.mem.usage > 70}">{{ server.mem.usage }} %</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" v-if="server.jvm" :class="{'text-danger': server.jvm.usage > 70}">{{ server.jvm.usage }} %</div></td>
              </tr>
              </tbody>
            </table>
          </div>
        </el-card>
      </el-col>

      <el-col :span="24" style="padding-right: 15px; padding-left: 15px; margin-bottom: 10px;">
        <el-card>
          <div slot="header" class="el-icon-help"><b> 服务器信息</b></div>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <table cellspacing="0" style="width: 100%;">
              <tbody>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">服务器名称</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" v-if="server.sys">{{ server.sys.computerName }}</div></td>
                <td class="el-table__cell is-leaf"><div class="cell">操作系统</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" v-if="server.sys">{{ server.sys.osName }}</div></td>
              </tr>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">服务器IP</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" v-if="server.sys">{{ server.sys.computerIp }}</div></td>
                <td class="el-table__cell is-leaf"><div class="cell">系统架构</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" v-if="server.sys">{{ server.sys.osArch }}</div></td>
              </tr>
              </tbody>
            </table>
          </div>
        </el-card>
      </el-col>

      <el-col :span="24" style="padding-right: 15px; padding-left: 15px; margin-bottom: 10px;">
        <el-card>
          <div slot="header" class="el-icon-set-up"><b> Java虚拟机信息</b></div>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <table cellspacing="0" style="width: 100%;table-layout:fixed;">
              <tbody>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">Java名称</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" v-if="server.jvm">{{ server.jvm.name }}</div></td>
                <td class="el-table__cell is-leaf"><div class="cell">Java版本</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" v-if="server.jvm">{{ server.jvm.version }}</div></td>
              </tr>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">启动时间</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" v-if="server.jvm">{{ server.jvm.startTime }}</div></td>
                <td class="el-table__cell is-leaf"><div class="cell">运行时长</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" v-if="server.jvm">{{ server.jvm.runTime }}</div></td>
              </tr>
              <tr>
                <td colspan="1" class="el-table__cell is-leaf"><div class="cell">安装路径</div></td>
                <td colspan="3" class="el-table__cell is-leaf"><div class="cell" v-if="server.jvm">{{ server.jvm.home }}</div></td>
              </tr>
              <tr>
                <td colspan="1" class="el-table__cell is-leaf"><div class="cell">项目路径</div></td>
                <td colspan="3" class="el-table__cell is-leaf"><div class="cell" v-if="server.sys">{{ server.sys.userDir }}</div></td>
              </tr>
              <tr>
                <td colspan="1" class="el-table__cell is-leaf"><div class="cell">运行参数</div></td>
                <td colspan="3" class="el-table__cell is-leaf"><div class="cell" v-if="server.jvm">{{ server.jvm.inputArgs }}</div></td>
              </tr>
              </tbody>
            </table>
          </div>
        </el-card>
      </el-col>

      <el-col :span="24" style="padding-right: 15px; padding-left: 15px; margin-bottom: 10px;">
        <el-card>
          <div slot="header" class="el-icon-copy-document"><b> 磁盘状态</b></div>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <table cellspacing="0" style="width: 100%;">
              <thead>
              <tr>
                <th class="el-table__cell el-table__cell is-leaf"><div class="cell">盘符路径</div></th>
                <th class="el-table__cell is-leaf"><div class="cell">文件系统</div></th>
                <th class="el-table__cell is-leaf"><div class="cell">盘符类型</div></th>
                <th class="el-table__cell is-leaf"><div class="cell">总大小</div></th>
                <th class="el-table__cell is-leaf"><div class="cell">可用大小</div></th>
                <th class="el-table__cell is-leaf"><div class="cell">已用大小</div></th>
                <th class="el-table__cell is-leaf"><div class="cell">已用百分比</div></th>
              </tr>
              </thead>
              <tbody v-if="server.sysFiles">
              <tr v-for="(sysFile, index) in server.sysFiles" :key="index">
                <td class="el-table__cell is-leaf"><div class="cell">{{ sysFile.dirName }}</div></td>
                <td class="el-table__cell is-leaf"><div class="cell">{{ sysFile.sysTypeName }}</div></td>
                <td class="el-table__cell is-leaf"><div class="cell">{{ sysFile.typeName }}</div></td>
                <td class="el-table__cell is-leaf"><div class="cell">{{ sysFile.total }}</div></td>
                <td class="el-table__cell is-leaf"><div class="cell">{{ sysFile.free }}</div></td>
                <td class="el-table__cell is-leaf"><div class="cell">{{ sysFile.used }}</div></td>
                <td class="el-table__cell is-leaf"><div class="cell" :class="{'text-danger': sysFile.usage > 70}">{{ sysFile.usage }}%</div></td>
              </tr>
              </tbody>
            </table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {Loading} from "element-ui";

let loadingInstance;

export default {
  name: "Server",
  data() {
    return {
      // 服务器信息
      server: []
    }
  },
  created() {
    this.getList();
    this.loading();
  },
  methods: {
    getList() {
      this.request.get("/server/").then(res => {
        if (res.code === 200) {
          this.server = res.data;
          this.closeLoading();
        }
      })
    },
    // 打开遮罩层
    loading() {
      loadingInstance = Loading.service({
        lock: true,
        text: "正在加载服务监控数据,请稍候!",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      })
    },
    // 关闭遮罩层
    closeLoading() {
      loadingInstance.close();
    }
  },
}
</script>

<style scoped>

</style>

具体的代码实现中有部分实体类并为列出,需要的家人们可以去源码中下载:

https://gitee.com/mr_xiongs_gitee/Jesus

感谢各位家人的观看喜欢的话点帮忙点赞👍👍👍哦

  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zyyn_未来可期

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值