Windows环境获取当前系统状态:
import cn.hutool.system.oshi.OshiUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.keydak.project.core.system.vo.SystemStatus; import org.springframework.stereotype.Service; import oshi.SystemInfo; import oshi.hardware.CentralProcessor; import oshi.hardware.GlobalMemory; import oshi.hardware.HardwareAbstractionLayer; import oshi.hardware.Sensors; import oshi.software.os.FileSystem; import oshi.software.os.OSFileStore; import oshi.software.os.OperatingSystem; import oshi.util.Util; import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.math.BigDecimal; import java.math.RoundingMode; /** * @author xjl */ @Service public class ISystemService { int OSHI_WAIT_SECOND = 1000; SystemInfo systemInfo = new SystemInfo(); HardwareAbstractionLayer hardwareAbstractionLayer = systemInfo.getHardware(); OperatingSystem osSystem = systemInfo.getOperatingSystem(); public SystemStatus getStatus() { //获取当前系统类型 String os = System.getProperty("os.name").toLowerCase(); //cpu信息 BigDecimal cpuP = null; //-------------------- 硬盘信息 FileSystem fileSystem = osSystem.getFileSystem(); long diskTotalSize = 0; long freeTotalSize = 0; OSFileStore[] fileStores = fileSystem.getFileStores(); for (int i = 0; (fileStores != null) && (i < fileStores.length); i++) { OSFileStore osFileStore = fileStores[i]; long storeTotalSpace = osFileStore.getTotalSpace(); diskTotalSize = diskTotalSize + storeTotalSpace; long storeFreeSpace = osFileStore.getUsableSpace(); freeTotalSize = freeTotalSize + storeFreeSpace; } BigDecimal diskUsedP = new BigDecimal(diskTotalSize - freeTotalSize).divide(new BigDecimal(diskTotalSize), 3, RoundingMode.HALF_UP).multiply(new BigDecimal(100)); //-------------------- 内存信息 GlobalMemory memory = OshiUtil.getMemory(); //内容总量 long total = memory.getTotal(); //剩余内存 long available = memory.getAvailable(); //使用量 long used = total - available; BigDecimal memoryP = new BigDecimal(used).divide(new BigDecimal(total), 3, RoundingMode.HALF_UP).multiply(new BigDecimal(100)); //CPU温度 Sensors sensors = hardwareAbstractionLayer.getSensors(); double cpuTemperature = sensors.getCpuTemperature(); if (os.contains("win")){ OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); String osJson = JSON.toJSONString(operatingSystemMXBean); JSONObject jsonObject = JSON.parseObject(osJson); cpuP = BigDecimal.valueOf(jsonObject.getDouble("systemCpuLoad") * 100); } return SystemStatus.builder() .memoryUsed(memoryP) .cpuLoadAvg(cpuP) .cpuTemperature(new BigDecimal(cpuTemperature).setScale(1, RoundingMode.HALF_UP)) .diskUsed(diskUsedP) .build(); } } import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.math.BigDecimal; @Data @AllArgsConstructor @NoArgsConstructor @Builder public class SystemStatus { //内存使用率 private BigDecimal memoryUsed; //磁盘使用率 private BigDecimal diskUsed; //cpu负载 private BigDecimal cpuLoadAvg; //cpu温度 private BigDecimal cpuTemperature; }
Linux环境获取当前系统状态(systemInfo.sh):
#!/bin/bash function addFloat() { local var1=$1 local var2=$2 local ret=`awk 'BEGIN{printf ("%.2f\n","'$var1'"+"'$var2'")}'` echo $ret } function subFloat() { local var1=$1 local var2=$2 #local ret=`awk 'BEGIN{print "'$var1'" - "'$var2'" } '` local ret=`awk 'BEGIN{printf ("%.2f\n","'$var1'"-"'$var2'")}'` echo $ret } function mulFloat() { local var1=$1 local var2=$2 local ret=`awk 'BEGIN{printf ("%.2f\n","'$var1'"*"'$var2'")}'` echo $ret } function divFloat() { local var1=$1 local var2=$2 # 小数个数 local decimalNum=2 # 判断是否有传入指定小数个数 if [ ! -z $3 ] then decimalNum=$3 fi local ret=`awk 'BEGIN{printf ("%."'$decimalNum'"f\n","'$var1'"/"'$var2'")}'` echo $ret } function getCoreNum() { echo `sensors | sed -n "/Core/p" | wc -l` } function getCpuLoadAvg() { echo `uptime | awk '{print $(NF-2)}'` } function getCoreAvgTemp() { IFS_OLD=$IFS IFS=$'\n' local val=0 for item in `sensors | sed -n "/Core/p" | awk '{print $3}' | grep -o "[0-9]*[\.]*[0-9]*"` do val=$(addFloat $val $item) done IFS=$IFS_OLD local len=$(getCoreNum) if [ $len -eq 0 ] then echo 0 else echo $(divFloat $val $len) fi } # ----- # 计算CPU利用率 # ----- cpuFree=`top -b -n 1 | sed -n "3,1p" | cut -d : -f 2- | cut -d , -f 4 | grep -o "[0-9]*\.[0-9]*"` cpuUsedPrecent=$(subFloat 100 $cpuFree) cpuLoadAvg=$(getCpuLoadAvg) # ------ # 计算内存利用率 # ------ totalMem=`top -b -n 1 | sed -n "4,1p" | cut -d : -f 2- | cut -d , -f 1 | grep -o "\s*[0-9.]*\s" | grep -o "[0-9.]*"` usedMem=`top -b -n 1 | sed -n "4,1p" | cut -d : -f 2- | cut -d , -f 3 | grep -o "\s*[0-9.]*\s" | grep -o "[0-9.]*"` # 通过 当前使用内存/总内存=内存利用率 memUsedPrecent=$(divFloat $usedMem $totalMem 4) # 将内存利用率扩大100倍 memUsedPrecent=$(mulFloat $memUsedPrecent 100) # ---------- # CPU平均温度 # ---------- cpuAvgTemp=$(getCoreAvgTemp) # ------------ # 磁盘使用率 # ------------ diskUsedPrecent=`df | sed -n "/\/dev\/sda/p" | grep -o "[0-9]*%" | grep -o "[0-9]*"` # 改变数值格式: xx.00 ,保持小数点2位 diskUsedPrecent=$(addFloat $diskUsedPrecent 0) # 输出结果 echo "$cpuLoadAvg $memUsedPrecent $cpuAvgTemp $diskUsedPrecent"
String systemStatusInfo ="/****/systemInfo.sh"; BigDecimal cpuP = null; default SystemStatus getStatus() { SystemStatus status = getSystemRunningStatus(); BigDecimal cpuLoadAvg = status.getCpuLoadAvg(); // 计算 (1 / logicalProcessorCount) * 100 BigDecimal processorCountBigDecimal = new BigDecimal(1) .divide(new BigDecimal(logicalProcessorCount), 10, RoundingMode.HALF_UP) .multiply(new BigDecimal(100)); cpuP = cpuLoadAvg.multiply(processorCountBigDecimal); } default SystemStatus getSystemRunningStatus() { String cmd = "sudo bash " + systemStatusInfo; String result = ""; try { result = RunTimeUtil.runCmd(cmd); } catch (Exception e) { e.printStackTrace(); } if (result.equals("")) return null; String[] statusInfo = result.replaceAll(",", "").split(" "); return SystemStatus.builder() .cpuLoadAvg(BigDecimal.valueOf(Float.parseFloat(statusInfo[0]))) .build(); }
@Slf4j public class RunTimeUtil { public static String runCmd(String cmd) throws Exception { log.debug("cmd:" + cmd); Process pro = null; BufferedReader errorStream = null; BufferedReader processStream = null; try { ProcessBuilder builder = new ProcessBuilder("/bin/sh", "-c", cmd); pro = builder.start(); errorStream = new BufferedReader(new InputStreamReader(pro.getErrorStream(), Charset.forName("UTF8"))); processStream = new BufferedReader(new InputStreamReader(pro.getInputStream(), Charset.forName("UTF8"))); StringBuilder infoSb = new StringBuilder(); String infoLine = null; while ((infoLine = processStream.readLine()) != null) { log.debug("脚本文件执行信息:" + infoLine); infoSb.append(infoLine).append("\n"); } StringBuilder errorSb = new StringBuilder(); String errorLine = null; while ((errorLine = errorStream.readLine()) != null) { log.debug("脚本文件错误:" + errorLine); errorSb.append(errorLine).append("\n"); } int code = pro.waitFor(); if (0 == code) { log.debug("脚本文件执行成功:" + code); return infoSb.toString(); } else { log.error("脚本文件{} 执行失败:{} {}", cmd, code, errorSb.toString()); return errorSb.toString(); } } finally { CloseUtil.close(errorStream); CloseUtil.close(processStream); if (pro != null) pro.destroy(); } } }