Springboot集成oshi远程监控主机
2020-12-17 本文已影响0人
千年的心
我们有时候需要去监控服务器的信息,在服务器达到某个阈值的时候需要报警,今天我们使用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();
// 遍历所有IP
for (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.测试
@Test
public void sys() {
for (int i = 0; i <100 ; i++) {
System.out.println(SysUtil.getInstance().get());
Util.sleep(1000);
}
}