搜索

普罗米修斯硬件监控系统


发布时间: 2022-11-24 18:42:03    浏览次数:63 次

pom引入

	    <!-- 19. 引入oshi依赖 -->
		<dependency>
			<groupId>com.github.oshi</groupId>
			<artifactId>oshi-core</artifactId>
			<version>5.3.6</version>
		</dependency>
开启定时器
@EnableScheduling//开启定时器
public class DiitMicroserviceDiitmapApplication  extends SpringBootServletInitializer

硬件信息自动记录

ToolOSInfo
import java.io.File;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Properties;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;

/**
 * <h5>描述:获取系统各类信息</h5>
 *
 */
public class ToolOSInfo {

    /**
     * 系统分隔符
     */
    private static final String SYSTEM_SEPARATOR = File.separator;
    /**
     * Unix分隔符
     */
    private static final String UNIX_SEPARATOR = "/";

    /**
     * Windows分隔符字符
     */
    private static final String WINDOWS_SEPARATOR = "\\";


    /**
     * <h5>功能:获取系统名称信息</h5>
     *
     * @return
     */
    public static String getOSName() {
        return System.getProperty("os.name").toLowerCase();
    }

    /**
     * <h5>功能:验证是否Linux系统</h5>
     *
     * @return
     */
    public static boolean isLinux(){
        return getOSName().indexOf("linux")>=0;
    }

    /**
     * <h5>功能:验证是否Linux系统</h5>
     *
     * @return
     */
    public static boolean isLinuxExt(){
        return SYSTEM_SEPARATOR.equals(UNIX_SEPARATOR);
    }

    /**
     * <h5>功能:验证是否Windows系统</h5>
     *
     * @return
     */
    public static boolean isWindows(){
        return getOSName().indexOf("windows")>=0;
    }

    /**
     * <h5>功能:验证是否Windows系统</h5>
     *
     * @return
     */
    public static boolean isWindowsExt(){
        return SYSTEM_SEPARATOR.equals(WINDOWS_SEPARATOR);
    }

    /**
     * <h5>功能:获取系统CPU信息</h5>
     *
     */
    public static JSONObject cpuInfo() throws InterruptedException {
        JSONObject cpuInfo = new JSONObject();

        SystemInfo systemInfo = new SystemInfo();
        // 获取硬件信息
        HardwareAbstractionLayer hardware = systemInfo.getHardware();
        // 获取处理器信息
        CentralProcessor processor = hardware.getProcessor();
        // 获取CPU信息
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        Thread.sleep(1000);
        long[] ticks = processor.getSystemCpuLoadTicks();

        long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.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 cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
        long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
        long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
        long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;

        //cpu核数
        cpuInfo.put("cpuProcessorCount", processor.getLogicalProcessorCount());
        //cpu系统使用率
        cpuInfo.put("cpuSysUse", new DecimalFormat("#.##%").format(cSys * 1.0 / totalCpu));
        //cpu用户使用率
        cpuInfo.put("cpuUserUse", new DecimalFormat("#.##%").format(user * 1.0 / totalCpu));
        //cpu当前等待率
        cpuInfo.put("cpuWaitRate", new DecimalFormat("#.##%").format(iowait * 1.0 / totalCpu));
        //cpu当前使用率
        cpuInfo.put("cpuNowRate", new DecimalFormat("#.##%").format(1.0 - (idle * 1.0 / totalCpu)));

        return  cpuInfo;
    }

    /**
     * <h5>功能:获取系统JVM信息</h5>
     *
     * @return
     */
    public static JSONObject getJvmInfo() {
        JSONObject jvmInfo = new JSONObject();
        Properties props = System.getProperties();
        Runtime runtime = Runtime.getRuntime();
        long jvmTotalMemoryByte = runtime.totalMemory();
        long freeMemoryByte = runtime.freeMemory();
        //jvm总内存
        jvmInfo.put("totalMemory", formatByte(runtime.totalMemory()));
        //空闲空间
        jvmInfo.put("freeMemory", formatByte(runtime.freeMemory()));
        //jvm最大可申请
        jvmInfo.put("maxMemory", formatByte(runtime.maxMemory()));
        //jvm已使用内存
        jvmInfo.put("useMemory", formatByte(jvmTotalMemoryByte - freeMemoryByte));
        //jvm内存使用率
        jvmInfo.put("useMemoryRate", new DecimalFormat("#.##%").format((jvmTotalMemoryByte - freeMemoryByte) * 1.0 / jvmTotalMemoryByte));
        //jdk版本
        jvmInfo.put("jdkVersion", props.getProperty("java.version"));
        //jdk路径
        jvmInfo.put("jdkPath", props.getProperty("java.home"));
        return jvmInfo;
    }

    /**
     * <h5>功能:获取系统内存信息</h5>
     *
     * @return
     */
    public static JSONObject getMemInfo() {
        JSONObject memInfo = new JSONObject();

        SystemInfo systemInfo = new SystemInfo();
        GlobalMemory memory = systemInfo.getHardware().getMemory();
        //总内存
        long totalByte = memory.getTotal();
        //剩余
        long acaliableByte = memory.getAvailable();
        //总内存
        memInfo.put("totalMemory", formatByte(totalByte));
        //剩余内存
        memInfo.put("freeMemory", formatByte(acaliableByte));
        //已用内存
        memInfo.put("useMemory", formatByte(totalByte - acaliableByte));
        //使用率
        memInfo.put("useMemoryRate", new DecimalFormat("#.##%").format((totalByte - acaliableByte) * 1.0 / totalByte));

        return memInfo;
    }

    /**
     * <h5>功能:获取系统盘符信息</h5>
     *
     * @return
     */
    public static JSONArray getSysFileInfo() {
        JSONObject sysFileInfo;
        JSONArray sysFiles = new JSONArray();
        SystemInfo systemInfo = new SystemInfo();
        OperatingSystem operatingSystem = systemInfo.getOperatingSystem();
        FileSystem fileSystem = operatingSystem.getFileSystem();
        List<OSFileStore> fsArray = fileSystem.getFileStores();
        for (OSFileStore fs : fsArray) {
            sysFileInfo = new JSONObject();
            //盘符路径
            sysFileInfo.put("sysDiskPath", fs.getMount());
            //总大小
            sysFileInfo.put("sysDiskTotal", formatByte(fs.getTotalSpace()));
            //剩余大小
            sysFileInfo.put("sysDiskFree", formatByte(fs.getUsableSpace()));
            //已经使用量
            sysFileInfo.put("sysDiskUsed", formatByte(fs.getTotalSpace() - fs.getUsableSpace()));
            //盘符类型
            sysFileInfo.put("sysDiskType", fs.getType());
            //文件类型
            sysFileInfo.put("fileType", fs.getName());
            if (fs.getTotalSpace() == 0) {
                //资源的使用率
                sysFileInfo.put("sysDiskUseRate", 0);
            } else {
                sysFileInfo.put("sysDiskUseRate",new DecimalFormat("#.##%").format((fs.getTotalSpace() - fs.getUsableSpace()) * 1.0 / fs.getTotalSpace()));
            }
            sysFiles.add(sysFileInfo);

        }

        return sysFiles;
    }

    // =================== private method ===================

    /**
     * 单位转换
     */
    public static String formatByte(long byteNumber) {
        //换算单位
        double FORMAT = 1024.0;
        double kbNumber = byteNumber / FORMAT;
        if (kbNumber < FORMAT) {
            return new DecimalFormat("#.##KB").format(kbNumber);
        }
        double mbNumber = kbNumber / FORMAT;
        if (mbNumber < FORMAT) {
            return new DecimalFormat("#.##MB").format(mbNumber);
        }
        double gbNumber = mbNumber / FORMAT;
        if (gbNumber < FORMAT) {
            return new DecimalFormat("#.##GB").format(gbNumber);
        }
        double tbNumber = gbNumber / FORMAT;
        return new DecimalFormat("#.##TB").format(tbNumber);
    }

    /**
     * 单位转换
     */
    public static Long formatToByteNum(String formatString) {
        double FORMAT = 1024.0;

        String strByte = formatString.substring(0, formatString.length() - 2);
        double byteNumber = Double.valueOf(strByte) * FORMAT;
        if (formatString.endsWith("KB")){
            return (long)byteNumber;
        }
        byteNumber = byteNumber * FORMAT;
        if (formatString.endsWith("MB")){
            return (long)byteNumber;
        }
        byteNumber = byteNumber * FORMAT;
        if (formatString.endsWith("GB")){
            return (long)byteNumber;
        }
        byteNumber = byteNumber * FORMAT;
        if (formatString.endsWith("TB")){
            return (long)byteNumber;
        }
        return 0l;
    }
}

CPU信息自动记录
Service
@EnableScheduling
public class OSHIService
	@Value("${server.addressUrl}")
    private String localIp;
	/**
     * cpu使用自动记录
     *
     * @throws InterruptedException
     */
//    @Scheduled(cron = "*/10 * * * * ?")//每10秒钟
//    @Scheduled(cron = "0 0/1 * * * ?")//每分钟执行一次
    @Scheduled(cron = "0 0 */1 * * ?")//每小时执行一次
    @Transactional
    public void ScheduledRecordingCpu() throws InterruptedException {
        JSONObject jsonObject = ToolOSInfo.cpuInfo();
        OSHICpu oshiCpu = new OSHICpu();
        //cpu核数
        oshiCpu.setCpuProcessorCount(jsonObject.getInteger("cpuProcessorCount"));
        //cpu系统使用率
        oshiCpu.setCpuSysUse(jsonObject.getString("cpuSysUse"));
        //cpu用户使用率
        oshiCpu.setCpuUserUse(jsonObject.getString("cpuUserUse"));
        //cpu当前等待率
        oshiCpu.setCpuWaitRate(jsonObject.getString("cpuWaitRate"));
        //cpu当前使用率
        oshiCpu.setCpuNowRate(jsonObject.getString("cpuNowRate"));
        //记录时间
        Timestamp recordingTime = new Timestamp(System.currentTimeMillis());
        oshiCpu.setRecordingTime(recordingTime);
        oshiCpu.setId(UUID.randomUUID().toString());
        oshiCpu.setLocalIp(localIp);
        oshiCpuMapper.insert(oshiCpu);
        oshiCpuMapper.deleteOut7Day();
    }
Mapper
<!-- 删除超过七天的记录 -->
    <delete id="deleteOut7Day" >
        delete from oshi_cpu where recording_time &lt; (now() - interval '7 day');
--         delete from oshi_cpu where recording_time &lt; (now() - interval '10 second');
    </delete>
Entity
import lombok.Data;
import org.apache.ibatis.type.Alias;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;

@Data
@Alias("OshiCpu")
@Table(name = "oshi_cpu")
public class OSHICpu {

    /**
     * 主键
     */
    @Id
    private String id;

    /**
     * cpu核数
     */
    @Column
    private Integer cpuProcessorCount;

    /**
     * cpu系统使用率
     */
    @Column
    private String cpuSysUse;

    /**
     * cpu用户使用率
     */
    @Column
    private String cpuUserUse;

    /**
     * cpu当前等待率
     */
    @Column
    private String cpuWaitRate;

    /**
     * cpu当前使用率
     */
    @Column
    private String cpuNowRate;

    /**
     * 记录的时间
     */
    @Column
    private Timestamp recordingTime;

    /**
     * 服务器ip
     */
    @Column
    private String localIp;

}

jvm信息自动记录
Service
@EnableScheduling
public class OSHIService	
	@Value("${server.addressUrl}")
    private String localIp;
	/**
     * jvm使用自动记录
     *
     * @throws InterruptedException
     */
    @Scheduled(cron = "0 0 */1 * * ?")//每小时执行一次
//        @Scheduled(cron = "*/10 * * * * ?")//每10秒钟
//    @Scheduled(cron = "0 0/1 * * * ?")//每分钟执行一次
    @Transactional
    public void ScheduledRecordingJvm() throws InterruptedException {
        JSONObject jsonObject = ToolOSInfo.getJvmInfo();
        OSHIJvm oshiJvm = new OSHIJvm();
        //jvm总内存
        oshiJvm.setTotalMemory(jsonObject.getString("totalMemory"));
        //空闲空间
        oshiJvm.setFreeMemory(jsonObject.getString("freeMemory"));
        //jvm最大可申请
        oshiJvm.setMaxMemory(jsonObject.getString("maxMemory"));
        //jvm已使用内存
        oshiJvm.setUseMemory(jsonObject.getString("useMemory"));
        //jvm内存使用率
        oshiJvm.setUseMemoryRate(jsonObject.getString("useMemoryRate"));
        //jdk版本
        oshiJvm.setJdkVersion(jsonObject.getString("jdkVersion"));
        //jdk路径
        oshiJvm.setJdkPath(jsonObject.getString("jdkPath"));
        Timestamp recordingTime = new Timestamp(System.currentTimeMillis());
        oshiJvm.setRecordingTime(recordingTime);
        oshiJvm.setId(UUID.randomUUID().toString());
        oshiJvm.setLocalIp(localIp);
        oshiJvmMapper.insert(oshiJvm);
        oshiJvmMapper.deleteOut7Day();
    }
Mapper
<!-- 删除超过七天的记录 -->
    <delete id="deleteOut7Day" >
        delete from oshi_jvm where recording_time &lt; (now() - interval '7 day');
--         delete from oshi_jvm where recording_time &lt; (now() - interval '10 second');
    </delete>
Entiry
import lombok.Data;
import org.apache.ibatis.type.Alias;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;

@Data
@Alias("OSHIJvm")
@Table(name = "oshi_jvm")
public class OSHIJvm {
    /**
     * 主键
     */
    @Id
    private String id;

    /**
     * jvm总内存
     */
    @Column
    private String totalMemory;

    /**
     * jvm空闲空间内存
     */
    @Column
    private String freeMemory;

    /**
     * jvm最大可申请
     */
    @Column
    private String maxMemory;

    /**
     * jvm已使用内存
     */
    @Column
    private String useMemory;

    /**
     * jvm内存使用率
     */
    @Column
    private String useMemoryRate;

    /**
     * jdk版本
     */
    @Column
    private String jdkVersion;

    /**
     * jdk路径
     */
    @Column
    private String jdkPath;

    /**
     * 记录的时间
     */
    @Column
    private Timestamp recordingTime;

    /**
     * 服务器ip
     */
    @Column
    private String localIp;
}

内存信息自动记录
Service
/**
     * 内存使用自动记录
     *
     * @throws InterruptedException
     */
    @Scheduled(cron = "0 0 */1 * * ?")//每小时执行一次
//        @Scheduled(cron = "*/10 * * * * ?")//每10秒钟
//    @Scheduled(cron = "0 0/1 * * * ?")//每分钟执行一次
    @Transactional
    public void ScheduledRecordingMemory() throws InterruptedException {
        JSONObject jsonObject = ToolOSInfo.getMemInfo();
        OSHIMemory oshiMemory = new OSHIMemory();
        //总内存
        oshiMemory.setTotalMemory(jsonObject.getString("totalMemory"));
        //空闲空间
        oshiMemory.setFreeMemory(jsonObject.getString("freeMemory"));
        //已使用内存
        oshiMemory.setUseMemory(jsonObject.getString("useMemory"));
        //内存使用率
        oshiMemory.setUseMemoryRate(jsonObject.getString("useMemoryRate"));
        Timestamp recordingTime = new Timestamp(System.currentTimeMillis());
        oshiMemory.setRecordingTime(recordingTime);
        oshiMemory.setId(UUID.randomUUID().toString());
        oshiMemory.setLocalIp(localIp);
        oshiMemoryMapper.insert(oshiMemory);
        oshiMemoryMapper.deleteOut7Day();
    }
Mapper
<!-- 删除超过七天的记录 -->
    <delete id="deleteOut7Day" >
        delete from oshi_memory where recording_time &lt; (now() - interval '7 day');
--         delete from oshi_memory where recording_time &lt; (now() - interval '10 second');
    </delete>
Entity
import lombok.Data;
import org.apache.ibatis.type.Alias;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;

@Data
@Alias("OSHIMemory")
@Table(name = "oshi_memory")
public class OSHIMemory {
    /**
     * 主键
     */
    @Id
    private String id;

    /**
     * 系统总内存
     */
    @Column
    private String totalMemory;

    /**
     * 系统空闲空间内存
     */
    @Column
    private String freeMemory;

    /**
     * 系统已使用内存
     */
    @Column
    private String useMemory;

    /**
     * 系统内存使用率
     */
    @Column
    private String useMemoryRate;

    /**
     * 记录的时间
     */
    @Column
    private Timestamp recordingTime;

    /**
     * 服务器ip
     */
    @Column
    private String localIp;
}

硬盘信息自动记录
Service
	/**
     * 硬盘使用自动记录
     *
     * @throws InterruptedException
     */
    @Scheduled(cron = "0 0 */1 * * ?")//每小时执行一次
//    @Scheduled(cron = "*/10 * * * * ?")//每10秒钟
//    @Scheduled(cron = "0 0/1 * * * ?")//每分钟执行一次
    @Transactional
    public void ScheduledRecordingSysDisk() throws InterruptedException {
        JSONArray jsonArray = ToolOSInfo.getSysFileInfo();
        Timestamp recordingTime = new Timestamp(System.currentTimeMillis());
        for (Object object : jsonArray) {
            JSONObject jsonObject = (JSONObject) object;
            OSHISysDisk oshiSysDisk = new OSHISysDisk();
            //盘符路径
            oshiSysDisk.setSysDiskPath(jsonObject.getString("sysDiskPath"));
            //总大小
            oshiSysDisk.setSysDiskTotal(jsonObject.getString("sysDiskTotal"));
            //剩余大小
            oshiSysDisk.setSysDiskFree(jsonObject.getString("sysDiskFree"));
            //已经使用量
            oshiSysDisk.setSysDiskUsed(jsonObject.getString("sysDiskUsed"));
            //盘符类型
            oshiSysDisk.setSysDiskType(jsonObject.getString("sysDiskType"));
            //文件类型
            oshiSysDisk.setFileType(jsonObject.getString("fileType"));
            //资源的使用率
            oshiSysDisk.setSysDiskUseRate(jsonObject.getString("sysDiskUseRate"));
            oshiSysDisk.setRecordingTime(recordingTime);
            oshiSysDisk.setId(UUID.randomUUID().toString());
            oshiSysDisk.setLocalIp(localIp);
            oshiSysDiskMapper.insert(oshiSysDisk);
        }
        oshiSysDiskMapper.deleteOut7Day();
    }
Mapper
<!-- 删除超过七天的记录 -->
    <delete id="deleteOut7Day" >
        delete from oshi_sys_disk where recording_time &lt; (now() - interval '7 day');
--         delete from oshi_sys_disk where recording_time &lt; (now() - interval '10 second');
    </delete>
Entity
import lombok.Data;
import org.apache.ibatis.type.Alias;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;

@Data
@Alias("OSHISysDisk")
@Table(name = "oshi_sys_disk")
public class OSHISysDisk {
    /**
     * 主键
     */
    @Id
    private String id;

    /**
     * 盘符路径
     */
    @Column
    private String sysDiskPath;

    /**
     * 总大小
     */
    @Column
    private String sysDiskTotal;

    /**
     * 剩余大小
     */
    @Column
    private String sysDiskFree;

    /**
     * 已经使用量
     */
    @Column
    private String sysDiskUsed;

    /**
     * 盘符类型
     */
    @Column
    private String sysDiskType;

    /**
     * 文件类型
     */
    @Column
    private String fileType;

    /**
     * 资源的使用率
     */
    @Column
    private String sysDiskUseRate;

    /**
     * 记录的时间
     */
    @Column
    private Timestamp recordingTime;

    /**
     * 服务器ip
     */
    @Column
    private String localIp;
}

获取7天的Cpu信息

Controller
	/**
     * 获取7天的Cpu信息
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/getCpuInfo7Day",method = RequestMethod.GET)
    @ResponseBody
    public APIResponse getCpuInfo7Day() {
        try{
            List<OSHICpu> cpuInfo7Day = oshiService.getCpuInfo7Day();
            return new APIResponse(ResponeCode.SUCCESS,"获取Cpu信息成功",cpuInfo7Day);
        }catch (Exception ex){
            return new APIResponse(ResponeCode.FAIL,"获取Cpu信息失败:"+ex.getMessage(),null);
        }
    }
Service
	/**
     * 获取7天的Cpu信息
     */
    public List<OSHICpu> getCpuInfo7Day() {
        List<OSHICpu> oshiCpuList = oshiCpuMapper.selectAll();

        if (oshiCpuList.size() != 0){
            List<OSHICpu> result = new ArrayList<>();
            //生成key为同一时间的map
            Map<String,List<OSHICpu>> sameTimeMap = new HashMap<>();
            for (OSHICpu oshiCpu : oshiCpuList) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String yyyyMMddHHmm = format.format(oshiCpu.getRecordingTime());
                List<OSHICpu> sameTimeList = sameTimeMap.getOrDefault(yyyyMMddHHmm, new ArrayList<>());
                sameTimeList.add(oshiCpu);
                sameTimeMap.put(yyyyMMddHHmm,sameTimeList);
            }
            for (Map.Entry<String, List<OSHICpu>> entry : sameTimeMap.entrySet()){
                List<OSHICpu> sameTimeList = entry.getValue();
                OSHICpu oshiCpu = new OSHICpu();
                Integer cpuProcessorCount = 0;
                Double cpuSysUseCount = 0d;
                Double cpuUserUseCount = 0d;
                Double cpuWaitRateCount = 0d;
                Double cpuNowRateCount = 0d;
                for (OSHICpu cpu : sameTimeList) {
                    cpuProcessorCount += cpu.getCpuProcessorCount();
                    //计算 CpuSysUse
                    double cpuSysUse = Double.parseDouble(cpu.getCpuSysUse().substring(0,cpu.getCpuSysUse().length()-1))*0.01;
                    double cpuSysUseNum = cpu.getCpuProcessorCount() * cpuSysUse;
                    cpuSysUseCount += cpuSysUseNum;
                    //计算 CpuUserUse
                    double cpuUserUse = Double.parseDouble(cpu.getCpuUserUse().substring(0,cpu.getCpuUserUse().length()-1))*0.01;
                    double cpuUserUseNum = cpu.getCpuProcessorCount() * cpuUserUse;
                    cpuUserUseCount += cpuUserUseNum;
                    //计算 CpuWaitRate
                    double CpuWaitRate = Double.parseDouble(cpu.getCpuWaitRate().substring(0,cpu.getCpuWaitRate().length()-1))*0.01;
                    double cpuWaitRateNum = cpu.getCpuProcessorCount() * CpuWaitRate;
                    cpuWaitRateCount += cpuWaitRateNum;
                    //计算 CpuNowRate
                    double cpuNowRate = Double.parseDouble(cpu.getCpuNowRate().substring(0,cpu.getCpuNowRate().length()-1))*0.01;
                    double cpuNowRateNum = cpu.getCpuProcessorCount() * cpuNowRate;
                    cpuNowRateCount += cpuNowRateNum;
                }
                oshiCpu.setCpuProcessorCount(cpuProcessorCount);
                //计算CpuSysUse
                Double cpuSysUseDouble = cpuSysUseCount / cpuProcessorCount;
                String cpuSysUse = new DecimalFormat("#.##%").format(cpuSysUseDouble);
                oshiCpu.setCpuSysUse(cpuSysUse);
                //计算CpuUserUse
                Double cpuUserUseDouble = cpuUserUseCount / cpuProcessorCount;
                String cpuUserUse = new DecimalFormat("#.##%").format(cpuUserUseDouble);
                oshiCpu.setCpuUserUse(cpuUserUse);
                //计算 CpuWaitRate
                Double cpuWaitRateDouble = cpuWaitRateCount / cpuProcessorCount;
                String cpuWaitRate = new DecimalFormat("#.##%").format(cpuWaitRateDouble);
                oshiCpu.setCpuWaitRate(cpuWaitRate);
                //计算 CpuNowRate
                Double cpuNowRateDouble = cpuNowRateCount / cpuProcessorCount;
                String cpuNowRate = new DecimalFormat("#.##%").format(cpuNowRateDouble);
                oshiCpu.setCpuNowRate(cpuNowRate);
                //添加记录时间
                oshiCpu.setRecordingTime(sameTimeList.get(0).getRecordingTime());
                result.add(oshiCpu);
            }

            result = result.stream().sorted(Comparator.comparing(OSHICpu::getRecordingTime)).collect(Collectors.toList());
            return result;
        }else {
            return null;
        }
    }
Entity
import lombok.Data;
import org.apache.ibatis.type.Alias;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;

@Data
@Alias("OshiCpu")
@Table(name = "oshi_cpu")
public class OSHICpu {

    /**
     * 主键
     */
    @Id
    private String id;

    /**
     * cpu核数
     */
    @Column
    private Integer cpuProcessorCount;

    /**
     * cpu系统使用率
     */
    @Column
    private String cpuSysUse;

    /**
     * cpu用户使用率
     */
    @Column
    private String cpuUserUse;

    /**
     * cpu当前等待率
     */
    @Column
    private String cpuWaitRate;

    /**
     * cpu当前使用率
     */
    @Column
    private String cpuNowRate;

    /**
     * 记录的时间
     */
    @Column
    private Timestamp recordingTime;

    /**
     * 服务器ip
     */
    @Column
    private String localIp;

}

获取7天的Jvm信息

Controller
	/**
     * 获取7天的Jvm信息
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/getJvmInfo7Day",method = RequestMethod.GET)
    @ResponseBody
    public APIResponse getJvmInfo7Day() {
        try{
            List<OSHIJvm> jvmInfo7Day = oshiService.getJvmInfo7Day();

            return new APIResponse(ResponeCode.SUCCESS,"获取Jvm信息成功",jvmInfo7Day);
        }catch (Exception ex){
            return new APIResponse(ResponeCode.FAIL,"获取Jvm信息失败:"+ex.getMessage(),null);
        }
    }
Service
	/**
     * 获取7天的Jvm信息
     */
    public List<OSHIJvm> getJvmInfo7Day() {
        List<OSHIJvm> oshiJvmList = oshiJvmMapper.selectAll();
        if (oshiJvmList.size() != 0){
            List<OSHIJvm> result = new ArrayList<>();
            //生成key为同一时间的map
            Map<String,List<OSHIJvm>> sameTimeMap = new HashMap<>();
            for (OSHIJvm oshiJvm : oshiJvmList) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String yyyyMMddHHmm = format.format(oshiJvm.getRecordingTime());
                List<OSHIJvm> sameTimeList = sameTimeMap.getOrDefault(yyyyMMddHHmm, new ArrayList<>());
                sameTimeList.add(oshiJvm);
                sameTimeMap.put(yyyyMMddHHmm,sameTimeList);
            }
            //去计算
            for (Map.Entry<String, List<OSHIJvm>> entry : sameTimeMap.entrySet()){
                List<OSHIJvm> sameTimeList = entry.getValue();
                OSHIJvm oshiJvm = new OSHIJvm();
                // totalMemory 的位数Long
                Long totalMemoryLong = 0l;
                // freeMemory 的位数Long
                Long freeMemoryLong = 0l;
                // maxMemory 的位数Long
                Long maxMemoryLong = 0l;
                // useMemory 的位数Long
                Long useMemoryLong = 0l;
                // useMemoryRate 的位数Long
                Double useMemoryRateLong = 0d;
                for (OSHIJvm jvm : sameTimeList) {
                    //计算 totalMemory 的位数
                    totalMemoryLong += ToolOSInfo.formatToByteNum(jvm.getTotalMemory());
                    //计算 freeMemory 的位数
                    freeMemoryLong += ToolOSInfo.formatToByteNum(jvm.getFreeMemory());
                    //计算 maxMemory 的位数
                    maxMemoryLong += ToolOSInfo.formatToByteNum(jvm.getMaxMemory());
                    //计算 useMemory 的位数
                    useMemoryLong += ToolOSInfo.formatToByteNum(jvm.getUseMemory());
                    //计算 useMemoryRate
                    double useMemoryRate = Double.parseDouble(jvm.getUseMemoryRate().substring(0,jvm.getUseMemoryRate().length()-1))*0.01;
                    double useMemoryRateNum = ToolOSInfo.formatToByteNum(jvm.getTotalMemory()) * useMemoryRate;
                    useMemoryRateLong += useMemoryRateNum;
                }
                //计算 totalMemory
                String totalMemory = ToolOSInfo.formatByte(totalMemoryLong);
                oshiJvm.setTotalMemory(totalMemory);
                //计算 freeMemory
                String freeMemory = ToolOSInfo.formatByte(freeMemoryLong);
                oshiJvm.setFreeMemory(freeMemory);
                //计算 maxMemory
                String maxMemory = ToolOSInfo.formatByte(maxMemoryLong);
                oshiJvm.setFreeMemory(maxMemory);
                //计算 useMemory
                String useMemory = ToolOSInfo.formatByte(useMemoryLong);
                oshiJvm.setFreeMemory(useMemory);
                //计算 useMemoryRate
                Double useMemoryRateDouble = useMemoryRateLong / totalMemoryLong;
                String useMemoryRate = new DecimalFormat("#.##%").format(useMemoryRateDouble);
                oshiJvm.setUseMemoryRate(useMemoryRate);

                //添加记录时间
                oshiJvm.setRecordingTime(sameTimeList.get(0).getRecordingTime());
                result.add(oshiJvm);
            }

            result = result.stream().sorted(Comparator.comparing(OSHIJvm::getRecordingTime)).collect(Collectors.toList());
            return result;
        }else {
            return null;
        }
    }
Entity
import lombok.Data;
import org.apache.ibatis.type.Alias;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;

@Data
@Alias("OSHIJvm")
@Table(name = "oshi_jvm")
public class OSHIJvm {
    /**
     * 主键
     */
    @Id
    private String id;

    /**
     * jvm总内存
     */
    @Column
    private String totalMemory;

    /**
     * jvm空闲空间内存
     */
    @Column
    private String freeMemory;

    /**
     * jvm最大可申请
     */
    @Column
    private String maxMemory;

    /**
     * jvm已使用内存
     */
    @Column
    private String useMemory;

    /**
     * jvm内存使用率
     */
    @Column
    private String useMemoryRate;

    /**
     * jdk版本
     */
    @Column
    private String jdkVersion;

    /**
     * jdk路径
     */
    @Column
    private String jdkPath;

    /**
     * 记录的时间
     */
    @Column
    private Timestamp recordingTime;

    /**
     * 服务器ip
     */
    @Column
    private String localIp;
}

获取7天的内存信息

Controller
	/**
     * 获取7天的内存信息
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/getMemoryInfo7Day",method = RequestMethod.GET)
    @ResponseBody
    public APIResponse getMemoryInfo7Day() {
        try{
            List<OSHIMemory> memoryInfo7Day = oshiService.getMemoryInfo7Day();
            return new APIResponse(ResponeCode.SUCCESS,"获取内存信息成功",memoryInfo7Day);
        }catch (Exception ex){
            return new APIResponse(ResponeCode.FAIL,"获取内存信息失败:"+ex.getMessage(),null);
        }
    }
Service
/**
     * 获取7天的内存信息
     */
    public List<OSHIMemory> getMemoryInfo7Day() {
        List<OSHIMemory> oshiMemoryList = oshiMemoryMapper.selectAll();
        if (oshiMemoryList.size() != 0){
            List<OSHIMemory> result = new ArrayList<>();
            //生成key为同一时间的map
            Map<String,List<OSHIMemory>> sameTimeMap = new HashMap<>();
            for (OSHIMemory oshiMemory : oshiMemoryList) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String yyyyMMddHHmm = format.format(oshiMemory.getRecordingTime());
                List<OSHIMemory> sameTimeList = sameTimeMap.getOrDefault(yyyyMMddHHmm, new ArrayList<>());
                sameTimeList.add(oshiMemory);
                sameTimeMap.put(yyyyMMddHHmm,sameTimeList);
            }
            //去计算
            for (Map.Entry<String, List<OSHIMemory>> entry : sameTimeMap.entrySet()){
                List<OSHIMemory> sameTimeList = entry.getValue();
                OSHIMemory oshiMemory = new OSHIMemory();
                // totalMemory 的位数Long
                Long totalMemoryLong = 0l;
                // freeMemory 的位数Long
                Long freeMemoryLong = 0l;
                // useMemory 的位数Long
                Long useMemoryLong = 0l;
                // useMemoryRate 的位数Long
                Double useMemoryRateLong = 0d;
                for (OSHIMemory memory : sameTimeList) {
                    //计算 totalMemory 的位数
                    totalMemoryLong += ToolOSInfo.formatToByteNum(memory.getTotalMemory());
                    //计算 freeMemory 的位数
                    freeMemoryLong += ToolOSInfo.formatToByteNum(memory.getFreeMemory());
                    //计算 useMemory 的位数
                    useMemoryLong += ToolOSInfo.formatToByteNum(memory.getUseMemory());
                    //计算 useMemoryRate
                    double useMemoryRate = Double.parseDouble(memory.getUseMemoryRate().substring(0,memory.getUseMemoryRate().length()-1))*0.01;
                    double useMemoryRateNum = ToolOSInfo.formatToByteNum(memory.getTotalMemory()) * useMemoryRate;
                    useMemoryRateLong += useMemoryRateNum;
                }
                //计算 totalMemory
                String totalMemory = ToolOSInfo.formatByte(totalMemoryLong);
                oshiMemory.setTotalMemory(totalMemory);
                //计算 freeMemory
                String freeMemory = ToolOSInfo.formatByte(freeMemoryLong);
                oshiMemory.setFreeMemory(freeMemory);
                //计算 useMemory
                String useMemory = ToolOSInfo.formatByte(useMemoryLong);
                oshiMemory.setFreeMemory(useMemory);
                //计算 useMemoryRate
                Double useMemoryRateDouble = useMemoryRateLong / totalMemoryLong;
                String useMemoryRate = new DecimalFormat("#.##%").format(useMemoryRateDouble);
                oshiMemory.setUseMemoryRate(useMemoryRate);

                //添加记录时间
                oshiMemory.setRecordingTime(sameTimeList.get(0).getRecordingTime());
                result.add(oshiMemory);
            }

            result = result.stream().sorted(Comparator.comparing(OSHIMemory::getRecordingTime)).collect(Collectors.toList());
            return result;
        }else {
            return null;
        }
    }
Entity
import lombok.Data;
import org.apache.ibatis.type.Alias;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;

@Data
@Alias("OSHIMemory")
@Table(name = "oshi_memory")
public class OSHIMemory {
    /**
     * 主键
     */
    @Id
    private String id;

    /**
     * 系统总内存
     */
    @Column
    private String totalMemory;

    /**
     * 系统空闲空间内存
     */
    @Column
    private String freeMemory;

    /**
     * 系统已使用内存
     */
    @Column
    private String useMemory;

    /**
     * 系统内存使用率
     */
    @Column
    private String useMemoryRate;

    /**
     * 记录的时间
     */
    @Column
    private Timestamp recordingTime;

    /**
     * 服务器ip
     */
    @Column
    private String localIp;
}

获取7天的硬盘信息

Controller
	/**
     * 获取7天的硬盘信息
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/getSysDiskInfo7Day",method = RequestMethod.GET)
    @ResponseBody
    public APIResponse getSysDiskInfo7Day() {
        try{
            List<OSHISysDisk> data = oshiService.getSysDiskInfo7Day();
            return new APIResponse(ResponeCode.SUCCESS,"获取硬盘信息成功",data);
        }catch (Exception ex){
            return new APIResponse(ResponeCode.FAIL,"获取硬盘信息失败:"+ex.getMessage(),null);
        }
    }
Service
/**
     * 获取7天的硬盘信息
     */
    public List<OSHISysDisk> getSysDiskInfo7Day() {
        List<OSHISysDisk> oshiSysDiskList = oshiSysDiskMapper.selectAll();
        if (oshiSysDiskList.size() != 0){
            List<OSHISysDisk> result = new ArrayList<>();
            //生成key为同一时间的map
            Map<String,List<OSHISysDisk>> sameTimeMap = new HashMap<>();
            for (OSHISysDisk oshiSysDisk : oshiSysDiskList) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String yyyyMMddHHmm = format.format(oshiSysDisk.getRecordingTime());
                List<OSHISysDisk> sameTimeList = sameTimeMap.getOrDefault(yyyyMMddHHmm, new ArrayList<>());
                sameTimeList.add(oshiSysDisk);
                sameTimeMap.put(yyyyMMddHHmm,sameTimeList);
            }
            //去计算
            for (Map.Entry<String, List<OSHISysDisk>> entry : sameTimeMap.entrySet()){
                List<OSHISysDisk> sameTimeList = entry.getValue();
                OSHISysDisk oshiSysDisk = new OSHISysDisk();
                // sysDiskTotal 的位数Long
                Long sysDiskTotalLong = 0l;
                // sysDiskFree 的位数Long
                Long sysDiskFreeLong = 0l;
                // sysDiskUsed 的位数Long
                Long sysDiskUsedLong = 0l;
                // sysDiskUseRate 的位数Long
                Double sysDiskUseRateLong = 0d;
                for (OSHISysDisk sysDisk : sameTimeList) {
                    //计算 sysDiskTotal 的位数
                    sysDiskTotalLong += ToolOSInfo.formatToByteNum(sysDisk.getSysDiskTotal());
                    //计算 sysDiskFree 的位数
                    sysDiskFreeLong += ToolOSInfo.formatToByteNum(sysDisk.getSysDiskFree());
                    //计算 sysDiskUsed 的位数
                    sysDiskUsedLong += ToolOSInfo.formatToByteNum(sysDisk.getSysDiskUsed());
                    //计算 sysDiskUseRate
                    double sysDiskUseRate = Double.parseDouble(sysDisk.getSysDiskUseRate().substring(0,sysDisk.getSysDiskUseRate().length()-1))*0.01;
                    double sysDiskUseRateNum = ToolOSInfo.formatToByteNum(sysDisk.getSysDiskTotal()) * sysDiskUseRate;
                    sysDiskUseRateLong += sysDiskUseRateNum;
                }
                //计算 sysDiskTotal
                String sysDiskTotal = ToolOSInfo.formatByte(sysDiskTotalLong);
                oshiSysDisk.setSysDiskTotal(sysDiskTotal);
                //计算 sysDiskFree
                String sysDiskFree = ToolOSInfo.formatByte(sysDiskFreeLong);
                oshiSysDisk.setSysDiskFree(sysDiskFree);
                //计算 sysDiskUsed
                String sysDiskUsed = ToolOSInfo.formatByte(sysDiskUsedLong);
                oshiSysDisk.setSysDiskUsed(sysDiskUsed);
                //计算 sysDiskUseRate
                Double sysDiskUseRateDouble = sysDiskUseRateLong / sysDiskTotalLong;
                String sysDiskUseRate = new DecimalFormat("#.##%").format(sysDiskUseRateDouble);
                oshiSysDisk.setSysDiskUseRate(sysDiskUseRate);

                //添加记录时间
                oshiSysDisk.setRecordingTime(sameTimeList.get(0).getRecordingTime());
                result.add(oshiSysDisk);
            }

            result = result.stream().sorted(Comparator.comparing(OSHISysDisk::getRecordingTime)).collect(Collectors.toList());
            return result;
        }else {
            return null;
        }
    }
Enity
import lombok.Data;
import org.apache.ibatis.type.Alias;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;

@Data
@Alias("OSHISysDisk")
@Table(name = "oshi_sys_disk")
public class OSHISysDisk {
    /**
     * 主键
     */
    @Id
    private String id;

    /**
     * 盘符路径
     */
    @Column
    private String sysDiskPath;

    /**
     * 总大小
     */
    @Column
    private String sysDiskTotal;

    /**
     * 剩余大小
     */
    @Column
    private String sysDiskFree;

    /**
     * 已经使用量
     */
    @Column
    private String sysDiskUsed;

    /**
     * 盘符类型
     */
    @Column
    private String sysDiskType;

    /**
     * 文件类型
     */
    @Column
    private String fileType;

    /**
     * 资源的使用率
     */
    @Column
    private String sysDiskUseRate;

    /**
     * 记录的时间
     */
    @Column
    private Timestamp recordingTime;

    /**
     * 服务器ip
     */
    @Column
    private String localIp;
}

获取7天的硬盘使用个数信息

Controller
	/**
     * 获取7天的硬盘使用个数信息
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/getSysDiskTotalUse7Day",method = RequestMethod.GET)
    @ResponseBody
    public APIResponse getSysDiskTotalUse7Day() {
        try{
            List<SysDiskTotalUse> data = oshiService.getSysDiskTotalUse7Day();
            return new APIResponse(ResponeCode.SUCCESS,"获取硬盘信息成功",data);
        }catch (Exception ex){
            return new APIResponse(ResponeCode.FAIL,"获取硬盘信息失败:"+ex.getMessage(),null);
        }
    }
Service
public List<SysDiskTotalUse> getSysDiskTotalUse7Day() {
        List<OSHISysDisk> oshiSysDiskList = oshiSysDiskMapper.selectAll();
        oshiSysDiskList = oshiSysDiskList.stream().sorted(Comparator.comparing(OSHISysDisk::getRecordingTime)).collect(Collectors.toList());
        Set<Timestamp> timeSet = new LinkedHashSet<>();
        for (OSHISysDisk oshiSysDisk : oshiSysDiskList) {
            timeSet.add(oshiSysDisk.getRecordingTime());
        }
        List<List<OSHISysDisk>> data = new ArrayList<>();
        for (Timestamp timestamp : timeSet) {
            List<OSHISysDisk> sysDiskGroupByTimeList = new ArrayList<>();
            for (OSHISysDisk oshiSysDisk : oshiSysDiskList) {
                if (timestamp.equals(oshiSysDisk.getRecordingTime())){
                    sysDiskGroupByTimeList.add(oshiSysDisk);
                }
            }
            if (sysDiskGroupByTimeList.size() != 0){
                data.add(sysDiskGroupByTimeList);
            }
        }
        List<SysDiskTotalUse> result = new ArrayList<>();
        for (List<OSHISysDisk> list : data) {
            SysDiskTotalUse sysDiskTotalUse = new SysDiskTotalUse();
            Set<String> diskNumSet = new HashSet();
            long byteNumber = 0;
            for (OSHISysDisk oshiSysDisk : list) {
                diskNumSet.add(oshiSysDisk.getFileType());
                sysDiskTotalUse.setRecordingTime(oshiSysDisk.getRecordingTime());
                byteNumber += ToolOSInfo.formatToByteNum(oshiSysDisk.getSysDiskUsed());
            }
            sysDiskTotalUse.setDiskNum(diskNumSet.size());
            String formatByte = ToolOSInfo.formatByte(byteNumber);
            sysDiskTotalUse.setDiskTotalUsageUnit(formatByte.substring(formatByte.length()-2));
            sysDiskTotalUse.setDiskTotalUsageNum(Double.valueOf(formatByte.substring(0,formatByte.length()-2)));
            result.add(sysDiskTotalUse);
        }
        return result;
    }
Entity
import lombok.Data;
import org.apache.ibatis.type.Alias;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;

@Data
@Alias("OSHISysDisk")
@Table(name = "oshi_sys_disk")
public class OSHISysDisk {
    /**
     * 主键
     */
    @Id
    private String id;

    /**
     * 盘符路径
     */
    @Column
    private String sysDiskPath;

    /**
     * 总大小
     */
    @Column
    private String sysDiskTotal;

    /**
     * 剩余大小
     */
    @Column
    private String sysDiskFree;

    /**
     * 已经使用量
     */
    @Column
    private String sysDiskUsed;

    /**
     * 盘符类型
     */
    @Column
    private String sysDiskType;

    /**
     * 文件类型
     */
    @Column
    private String fileType;

    /**
     * 资源的使用率
     */
    @Column
    private String sysDiskUseRate;

    /**
     * 记录的时间
     */
    @Column
    private Timestamp recordingTime;

    /**
     * 服务器ip
     */
    @Column
    private String localIp;
}
免责声明 普罗米修斯硬件监控系统,资源类别:文本, 浏览次数:63 次, 文件大小:-- , 由本站蜘蛛搜索收录2022-11-24 06:42:03。此页面由程序自动采集,只作交流和学习使用,本站不储存任何资源文件,如有侵权内容请联系我们举报删除, 感谢您对本站的支持。 原文链接:https://www.cnblogs.com/ideaAI/p/16803396.html