我們有時(shí)候需要去監(jiān)控服務(wù)器的信息,在服務(wù)器達(dá)到某個(gè)閾值的時(shí)候需要報(bào)警,今天我們使用Springboot結(jié)合oshi來獲取系統(tǒng)信息
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.編寫通用信息實(shí)體
import lombok.Data;
/**
* @author lieber
*/
@Data
public class BaseInfo {
/**
* 總大小
*/
private String total;
/**
* 空閑
*/
private String available;
/**
* 已使用
*/
private String used;
/**
* 使用率
*/
private String usageRate;
}
CPU信息實(shí)體
import lombok.Data;
/**
* @author lieber
*/
@Data
public class CpuInfo {
/**
* CPU名稱
*/
private String name;
/**
* 物理CPU
*/
private int number;
/**
* 邏輯CPU
*/
private int logic;
/**
* 物理核心數(shù)
*/
private int core;
/**
* 空閑
*/
private String idle;
/**
* 使用
*/
private String used;
}
內(nèi)存信息實(shí)體
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* @author lieber
*/
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Data
public class MemoryInfo extends BaseInfo {
}
交換區(qū)信息實(shí)體
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* @author lieber
*/
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Data
public class SwapInfo extends BaseInfo {
}
磁盤信息實(shí)體
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* @author lieber
*/
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Data
public class DiskInfo extends BaseInfo {
}
系統(tǒng)信息實(shí)體
import lombok.Data;
/**
* @author lieber
*/
@Data
public class OsInfo {
private String name;
private String ip;
/**
* @author lieber
*/
private long runtime;
}
輸出信息實(shí)體
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;
// 查找網(wǎng)絡(luò)接口
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.測(cè)試
@Test
public void sys() {
for (int i = 0; i <100 ; i++) {
System.out.println(SysUtil.getInstance().get());
Util.sleep(1000);
}
}