我们有时候需要去监控服务器的信息,在服务器达到某个阈值的时候需要报警,今天我们使用Springboot结合oshi来获取系统信息

1.排除springboot(这里使用springboot 2.1.14.RELEASE)自带的jna和jna-platform

    compile('org.springframework.boot:spring-boot-starter-web') {exclude group: 'net.java.dev.jna', module: 'jna'exclude group: 'net.java.dev.jna', module: 'jna-platform'}

2.引入oshi和高版本jna

    compile 'com.github.oshi:oshi-core:5.3.6'compile 'net.java.dev.jna:jna:5.6.0'compile 'net.java.dev.jna:jna-platform:5.6.0'

3.编写通用信息实体

import lombok.Data;/*** @author lieber*/
@Data
public class BaseInfo {/*** 总大小*/private String total;/*** 空闲*/private String available;/*** 已使用*/private String used;/*** 使用率*/private String usageRate;}

CPU信息实体

import lombok.Data;/*** @author lieber*/
@Data
public class CpuInfo {/*** CPU名称*/private String name;/*** 物理CPU*/private int number;/*** 逻辑CPU*/private int logic;/*** 物理核心数*/private int core;/*** 空闲*/private String idle;/*** 使用*/private String used;}

内存信息实体

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;/*** @author lieber*/
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Data
public class MemoryInfo extends BaseInfo {
}

交换区信息实体

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;/*** @author lieber*/
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Data
public class SwapInfo extends BaseInfo {
}

磁盘信息实体

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;/*** @author lieber*/
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Data
public class DiskInfo extends BaseInfo {
}

系统信息实体

import lombok.Data;/*** @author lieber*/
@Data
public class OsInfo {private String name;private String ip;/*** @author lieber*/private long runtime;}

输出信息实体

import lombok.Builder;
import lombok.Data;/*** @author lieber*/
@Data
@Builder
public class SysInfo {private OsInfo os;private CpuInfo cpu;private MemoryInfo memory;private SwapInfo swap;private DiskInfo disk;private Long time;}

4.编写操作工具类

import com.xcqinzi.api.common.util.sys.model.*;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.hardware.VirtualMemory;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;
import oshi.util.FormatUtil;
import oshi.util.Util;import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.DecimalFormat;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;/*** @author lieber*/
public class SysUtil {private final DecimalFormat df = new DecimalFormat("0.00");private static SysUtil util;public static SysUtil getInstance() {if (util == null) {util = new SysUtil();}return util;}public SysInfo get() {SystemInfo si = new SystemInfo();OperatingSystem os = si.getOperatingSystem();HardwareAbstractionLayer hal = si.getHardware();CpuInfo cpuInfo = this.getCpuInfo(hal.getProcessor());MemoryInfo memoryInfo = this.getMemoryInfo(hal.getMemory());SwapInfo swapInfo = this.getSwapInfo(hal.getMemory());DiskInfo diskInfo = this.getDiskInfo(os);OsInfo osInfo = this.getOsInfo(os);return SysInfo.builder().cpu(cpuInfo).memory(memoryInfo).swap(swapInfo).disk(diskInfo).os(osInfo).time(System.currentTimeMillis()).build();}private CpuInfo getCpuInfo(CentralProcessor processor) {CpuInfo cpuInfo = new CpuInfo();// 基本信息cpuInfo.setName(processor.getProcessorIdentifier().getName());cpuInfo.setNumber(processor.getPhysicalPackageCount());cpuInfo.setCore(processor.getPhysicalProcessorCount());cpuInfo.setLogic(processor.getLogicalProcessorCount());// 占用信息long[] startTicks = processor.getSystemCpuLoadTicks();Util.sleep(1000);long[] endTicks = processor.getSystemCpuLoadTicks();long user = endTicks[CentralProcessor.TickType.USER.getIndex()] - startTicks[CentralProcessor.TickType.USER.getIndex()];long nice = endTicks[CentralProcessor.TickType.NICE.getIndex()] - startTicks[CentralProcessor.TickType.NICE.getIndex()];long sys = endTicks[CentralProcessor.TickType.SYSTEM.getIndex()] - startTicks[CentralProcessor.TickType.SYSTEM.getIndex()];long idle = endTicks[CentralProcessor.TickType.IDLE.getIndex()] - startTicks[CentralProcessor.TickType.IDLE.getIndex()];long ioWait = endTicks[CentralProcessor.TickType.IOWAIT.getIndex()] - startTicks[CentralProcessor.TickType.IOWAIT.getIndex()];long irq = endTicks[CentralProcessor.TickType.IRQ.getIndex()] - startTicks[CentralProcessor.TickType.IRQ.getIndex()];long softIrq = endTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - startTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];long steal = endTicks[CentralProcessor.TickType.STEAL.getIndex()] - startTicks[CentralProcessor.TickType.STEAL.getIndex()];long totalCpu = user + nice + sys + idle + ioWait + irq + softIrq + steal;if (totalCpu <= 0) {cpuInfo.setUsed("0");cpuInfo.setIdle("0");} else {cpuInfo.setUsed(df.format(100d * user / totalCpu + 100d * sys / totalCpu));cpuInfo.setIdle(df.format(100d * idle / totalCpu));}return cpuInfo;}private MemoryInfo getMemoryInfo(GlobalMemory memory) {MemoryInfo memoryInfo = new MemoryInfo();long total = memory.getTotal();long available = memory.getAvailable();long used = total - available;memoryInfo.setTotal(FormatUtil.formatBytes(total));memoryInfo.setAvailable(FormatUtil.formatBytes(available));memoryInfo.setUsed(FormatUtil.formatBytes(used));String usageRate = "0";if (total > 0 && used > 0) {usageRate = df.format(used * 100d / total);}memoryInfo.setUsageRate(usageRate);return memoryInfo;}private SwapInfo getSwapInfo(GlobalMemory memory) {SwapInfo swapInfo = new SwapInfo();VirtualMemory virtualMemory = memory.getVirtualMemory();long total = virtualMemory.getSwapTotal();long used = virtualMemory.getSwapUsed();long available = total - used;swapInfo.setTotal(FormatUtil.formatBytes(total));swapInfo.setAvailable(FormatUtil.formatBytes(available));swapInfo.setUsed(FormatUtil.formatBytes(used));String usageRate = "0";if (total > 0 && used > 0) {usageRate = df.format(used * 100d / total);}swapInfo.setUsageRate(usageRate);return swapInfo;}private DiskInfo getDiskInfo(OperatingSystem os) {DiskInfo diskInfo = new DiskInfo();FileSystem fileSystem = os.getFileSystem();List<OSFileStore> fsArray = fileSystem.getFileStores();String osName = System.getProperty("os.name");long available = 0, total = 0;if (osName.toLowerCase().startsWith("win")) {for (OSFileStore fs : fsArray) {available += fs.getUsableSpace();total += fs.getTotalSpace();}} else {Set<String> names = new HashSet<>(fsArray.size());for (OSFileStore fs : fsArray) {if (names.add(fs.getName())) {available = fs.getUsableSpace();total = fs.getTotalSpace();}}}long used = total - available;diskInfo.setTotal(FormatUtil.formatBytes(total));diskInfo.setAvailable(FormatUtil.formatBytes(available));diskInfo.setUsed(FormatUtil.formatBytes(used));String usageRate = "0";if (total > 0 && used > 0) {usageRate = df.format(used * 100d / total);}diskInfo.setUsageRate(usageRate);return diskInfo;}private OsInfo getOsInfo(OperatingSystem os) {OsInfo osInfo = new OsInfo();long time = ManagementFactory.getRuntimeMXBean().getStartTime();osInfo.setName(os.toString());osInfo.setIp(this.getIp());osInfo.setRuntime(System.currentTimeMillis() - time);return osInfo;}private String getIp() {try {InetAddress candidateAddress = null;// 查找网络接口for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) {NetworkInterface anInterface = interfaces.nextElement();// 遍历所有IPfor (Enumeration<InetAddress> inetAddresses = anInterface.getInetAddresses(); inetAddresses.hasMoreElements(); ) {InetAddress inetAddr = inetAddresses.nextElement();// 排除loopback类型地址if (!inetAddr.isLoopbackAddress()) {if (inetAddr.isSiteLocalAddress()) {return inetAddr.getHostAddress();} else if (candidateAddress == null) {candidateAddress = inetAddr;}}}}if (candidateAddress != null) {return candidateAddress.getHostAddress();}InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();if (jdkSuppliedAddress == null) {return "";}return jdkSuppliedAddress.getHostAddress();} catch (Exception e) {return "";}}
}

5.测试

    @Testpublic void sys() {for (int i = 0; i <100 ; i++) {System.out.println(SysUtil.getInstance().get());Util.sleep(1000);}}

Springboot集成oshi远程监控主机相关推荐

  1. Springboot集成Durid远程连接数据库一直报ERROR 1045 (28000): Access denied for user

    1.问题   Springboot集成Durid远程连接数据库时,发现一直报ERROR 1045 (28000): Access denied for user,显示密码错误,但在本地通过Navica ...

  2. Jenkins部署SpringBoot应用到远程服务器

    Jenkins部署SpringBoot应用到远程服务器 使用SpringBoot.SpringCloud写后台服务,也引入了当下比较流行的微服务的理念,模块也比较多.为了方便前期测试和后期线上部署更新 ...

  3. dubbo web工程示例_dubbo实战之二:与SpringBoot集成

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类和汇总,及配套源码,涉及Java.Docker.Kubernetes.DevO ...

  4. Java技术:SpringBoot集成FreeMarker生成word文件

                    今天给大家分享SpringBoot集成FreeMarker模板引擎生成word文件的用法,感兴趣的可以学一下,完整源码地址在文章末尾处,欢迎互相沟通交流! 一.什么是F ...

  5. SpringBoot集成Redis用法笔记

    今天给大家整理一下SpringBoot集成Redis用法笔记,希望对大家能有所帮助! 一.Redis优点介绍 1.速度快 不需要等待磁盘的IO,在内存之间进行的数据存储和查询,速度非常快.当然,缓存的 ...

  6. 后端:SpringBoot集成Swagger-Bootstrap-UI,界面美观!

    SpringBoot集成Swagger-Bootstrap-UI,界面美观.下面给大家介绍一下! 该开源项目GitHub地址: https://github.com/xiaoymin/Swagger- ...

  7. 记录spring、springboot集成apollo配置中心

    一, spring集成apollo,前提是apollo配置中心服务端已经在运行中 上面是我在阿里云服务搭建的apollo配置中心服务端,登录后的样子.没有搭建服务端的小伙伴,请先搭建好apollo的服 ...

  8. springboot集成Spring Security oauth2(八)

    由于公司项目需要,进行SpringBoot集成Spring Security oauth2,几乎搜寻网上所有大神的案例,苦苦不能理解,不能完全OK. 以下是借鉴各大神的代码,终于demo完工,请欣赏 ...

  9. SpringBoot集成Elasticsearch7.4 实战(一)

    在网上已经有好多关于Elasticsearch的介绍,就不在翻来覆去讲一些基本概念,大家感兴趣的可以自己去找一些资料巩固下.这次只为了顾及众多首次接触Elasticsearch,案例都讲的很浅显,还有 ...

最新文章

  1. wxWidgets3.0.2媒体播放器
  2. idea 使用 git 教程
  3. SQL查询语句的排序
  4. python.day05
  5. 基于STM32的波形发生器
  6. 用nodejs向163邮箱, gmail邮箱, qq邮箱发邮件, nodemailer使用详解
  7. Nginx基本数据结构之ngx_array_t
  8. 「leetcode」C++题解:15.三数之和 /3Sum 方法1:哈希法,方法2:排序+双指针,详细注释
  9. 微信表情包批量导出-2022年8月4日
  10. 中级计算机证书知识,计算机中级考哪些内容
  11. SNIFFER(嗅探器)基础知识
  12. Latex bare_jrnl模板报错:something‘s wrong--perhaps a missing\item. \end{thebibliography}
  13. 字写的不好没关系,还好我会python,轻轻一点就生成了艺术签名
  14. YOLOV7改进--添加CBAM注意力机制
  15. 华为服务器查看虚拟ip,裸金属服务器管理虚拟IP地址
  16. 使用云祺虚拟机备份软件备份H3C CAS 虚拟机
  17. #POW和POS的优势和劣势
  18. Python基础三、2、list列表练习题 引用随机数
  19. python2 + django 导出 excel 功能 接口示例代码(做记录)
  20. 树莓派4B 声音传感器AO模块

热门文章

  1. 手机微信怎样实现双开?教你在一部手机登录多个微信账号
  2. linux下强制杀死进程和解压缩命令
  3. 全球及中国互联网保险产业融资规模与投资竞争力研究报告2022版
  4. 第二阶段:1.流程图:10.visio绘制泳道图
  5. PHP 保留小数点后几位
  6. git查看本地分支是基于那个分支建立的
  7. sql 修改数据类型语句
  8. OpenCV_06 图像平滑:图像噪声+图像平滑+滤波
  9. Real-time voxel based 3D semantic mapping with a hand held RGB-D camera
  10. [matlab]用matlab建立word,并在word中写入文字和图片