Java获取Liunx服务器的cpu使用率、内存使用率以及磁盘使用率

前言:

本篇博客主要说明使用java程序如何获取liunx系统中的cpu使用率、内存使用率以及磁盘使用率,效果图如下:在这里插入图片描述

1.创建三个实体类,分别为cpu、内存以及磁盘相关信息:

cpu相关信息实体

package com.gdhengdian.monitorservice.domain.server;


import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * CPU相关信息
 * 
 *
 */
@Component
public class Cpu implements Serializable {

    /**
     * 核心数
     */
    private int cpuNum;

    /**
     * CPU总的使用率
     */
    private String total;

    /**
     * CPU系统使用率
     */
    private String sys;

    /**
     * CPU用户使用率
     */
    private String used;

    /**
     * CPU当前等待率
     */
    private String wait;

    /**
     * CPU当前空闲率
     */
    private String free;


    @Override
    public String toString() {
        return "Cpu{" +
                "核心数=" + getCpuNum() +
                ", CPU总的使用率=" + getTotal() +
                ", CPU系统使用率=" + getSys() +
                ", CPU用户使用率=" + getUsed() +
                ", CPU当前等待率=" + getWait() +
                ", CPU当前空闲率=" + getFree() +
                '}';
    }

    public int getCpuNum() {
        return cpuNum;
    }

    public void setCpuNum(int cpuNum) {
        this.cpuNum = cpuNum;
    }

    public String getTotal() {
        return total;
    }

    public void setTotal(String total) {
        this.total = total;
    }

    public String getSys() {
        return sys;
    }

    public void setSys(String sys) {
        this.sys = sys;
    }

    public String getUsed() {
        return used;
    }

    public void setUsed(String used) {
        this.used = used;
    }

    public String getWait() {
        return wait;
    }

    public void setWait(String wait) {
        this.wait = wait;
    }

    public String getFree() {
        return free;
    }

    public void setFree(String free) {
        this.free = free;
    }
}

内存相关信息实体:

package com.gdhengdian.monitorservice.domain.server;


import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * 內存相关信息
 * 
 * @author ruoyi
 */
@Component
public class Mem implements Serializable {
    private String usedRate;

    /**
     * 内存总量
     */
    private long total;

    /**
     * 已用内存
     */
    private long used;

    /**
     * 剩余内存
     */
    private long free;

    @Override
    public String toString() {
        return "Mem{" +
                "内存总量=" + getTotal() +
                ",同上=" + getUsed() +
                ", 剩余内存=" + getFree() +
                ", 使用率="+ getUsedRate() +
                '}';
    }

    public double getTotal()
    {
        return Arith.div(total, (1024 * 1024 * 1024), 2);
    }

    public void setTotal(long total)
    {
        this.total = total;
    }

    public double getUsed()
    {
        return Arith.div(used, (1024 * 1024 * 1024), 2);
    }

    public void setUsed(long used)
    {
        this.used = used;
    }

    public double getFree()
    {
        return Arith.div(free, (1024 * 1024 * 1024), 2);
    }

    public void setFree(long free)
    {
        this.free = free;
    }

    public double getUsage()
    {
        return Arith.mul(Arith.div(used, total, 4), 100);
    }

    public String getUsedRate() {
        return usedRate;
    }

    public void setUsedRate(String usedRate) {
        this.usedRate = usedRate;
    }
}

磁盘相关信息实体

package com.gdhengdian.monitorservice.domain.server;

import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * 系统文件相关信息
 *
 */
@Component
public class SysFile implements Serializable {
    /**
     * 盘符路径
     */
    private String dirName;

    /**
     * 盘符类型
     */
    private String sysTypeName;

    /**
     * 文件类型
     */
    private String typeName;

    /**
     * 总大小
     */
    private String total;

    /**
     * 剩余大小
     */
    private String free;

    /**
     * 已经使用量
     */
    private String used;

    /**
     * 资源的使用率
     */
    private String usage;

    @Override
    public String toString() {
        return "SysFile{" +
                "盘符路径='" + getDirName() + '\'' +
                ", 盘符类型='" + getSysTypeName() + '\'' +
                ", 文件类型='" + getTypeName() + '\'' +
                ", 总大小='" + getTotal() + '\'' +
                ", 剩余大小='" + getFree()+ '\'' +
                ", 已经使用量='" + getUsed() + '\'' +
                ", 资源的使用率=" + getUsage() +
                '}';
    }

    public String getDirName()
    {
        return dirName;
    }

    public void setDirName(String dirName)
    {
        this.dirName = dirName;
    }

    public String getSysTypeName()
    {
        return sysTypeName;
    }

    public void setSysTypeName(String sysTypeName)
    {
        this.sysTypeName = sysTypeName;
    }

    public String getTypeName()
    {
        return typeName;
    }

    public void setTypeName(String typeName)
    {
        this.typeName = typeName;
    }

    public String getTotal()
    {
        return total;
    }

    public void setTotal(String total)
    {
        this.total = total;
    }

    public String getFree()
    {
        return free;
    }

    public void setFree(String free)
    {
        this.free = free;
    }

    public String getUsed()
    {
        return used;
    }

    public void setUsed(String used)
    {
        this.used = used;
    }

    public String getUsage()
    {
        return usage;
    }

    public void setUsage(String usage)
    {
        this.usage = usage;
    }
}

2.再创建一个初始化服务器相关信息类:

package com.gdhengdian.monitorservice.domain;


import com.gdhengdian.monitorservice.domain.server.Arith;
import com.gdhengdian.monitorservice.domain.server.Cpu;
import com.gdhengdian.monitorservice.domain.server.Mem;
import com.gdhengdian.monitorservice.domain.server.SysFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
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;
import oshi.util.Util;
import oshi.hardware.CentralProcessor.TickType;

import java.text.NumberFormat;

/**
 * 服务器相关信息
 *
 */
@Component
public class Server
{
    
    private static final int OSHI_WAIT_SECOND = 2000;
    
    /**
     * CPU相关信息
     */
    @Autowired
    private Cpu cpu;
    /**
     * 內存相关信息
     */
    @Autowired
    private Mem mem;

    /**
     * 磁盘相关信息
     */
    @Autowired
    private SysFile sysFiles;

    /**
     * 获取磁盘,CPU,运行内存等数据
     * @throws Exception
     */
    public void copyTo() throws Exception
    {
        SystemInfo si = new SystemInfo();
        HardwareAbstractionLayer hal = si.getHardware();
        //cpux信息
        setCpuInfo(hal.getProcessor());
        //内存信息
        setMemInfo(hal.getMemory());
        //磁盘信息
        setSysFiles(si.getOperatingSystem());
    }

    /**
     * 设置CPU信息
     */
    private void setCpuInfo(CentralProcessor processor)
    {
        // CPU信息
        long[] prevTicks = processor.getSystemCpuLoadTicks();//cpu时钟1的计算出来的cpu各项指标(单位:节拍数)
        Util.sleep(OSHI_WAIT_SECOND);
        long[] ticks = processor.getSystemCpuLoadTicks(); //cpu时钟2的计算出来的cpu各项值(单位:节拍数)
        //以高优先级在用户级别执行时发生的CPU节拍数。
        Long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
        //CPU中断花销的节拍
        Long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
        //软中断花销的节拍
        Long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
        //系统监控程序为其它用户开启的cpu节拍,Only supported on Linux.
        Long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
        //CPU在内核空间运行的节拍花销
        Long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
        //用户进程对CPU的节拍花销
        Long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
        //CPU调用IO操作的节拍花销
        Long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
        //CPU处于空闲状态节拍花销
        Long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
        Long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
        Long cpuUsed = (cSys + user);
        double usedRate = cpuUsed.doubleValue() / totalCpu.doubleValue();
        // 创建一个数值格式化对象
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        String totalRate = numberFormat.format( usedRate * 100) ;//所占百分比
        cpu.setCpuNum(processor.getLogicalProcessorCount());
        cpu.setTotal(totalRate);
    }

    /**
     * 设置内存信息
     */
    private void setMemInfo(GlobalMemory memory) {

        long totalMem = memory.getTotal();
        mem.setTotal(totalMem);
        mem.setUsed(memory.getTotal() - memory.getAvailable());
        mem.setFree(memory.getAvailable());
        // 创建一个数值格式化对象
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        String usedRate = numberFormat.format(mem.getUsed() /  mem.getTotal() * 100);//所占百分比
        mem.setUsedRate(usedRate);
    }



    /**
     * 设置磁盘信息
     */
    private void setSysFiles(OperatingSystem os)
    {
        FileSystem fileSystem = os.getFileSystem();
        OSFileStore[] fsArray = fileSystem.getFileStores();
        long total = 0;
        long used = 0;
        long free = 0;
        for (OSFileStore fs : fsArray)
        {
            free += fs.getUsableSpace();
            total += fs.getTotalSpace();
        }
        used = total - free;
        double rate = Arith.mul(Arith.div(used, total, 4), 100);
        sysFiles.setUsage(new StringBuffer().append(rate).toString());
    }

    @Override
    public String toString() {
        return "Server{" +
                "cpu=" + getCpu() +
                "\n, memory=" + getMem() +
                ",\n sysFiles=" + getSysFiles() +
                '}';
    }

    public Cpu getCpu() {
        return cpu;
    }

    public void setCpu(Cpu cpu) {
        this.cpu = cpu;
    }

    public Mem getMem() {
        return mem;
    }

    public void setMem(Mem mem) {
        this.mem = mem;
    }

    public SysFile getSysFiles() {
        return sysFiles;
    }

    public void setSysFiles(SysFile sysFiles) {
        this.sysFiles = sysFiles;
    }
}

3.然后创建一个页面显示VO类:

package com.gdhengdian.monitorservice.domain;


import org.springframework.stereotype.Component;

import java.io.Serializable;

@Component
public class SystemResourceInfo implements Serializable {
    /**
     * CPU相关信息
     */
    private String cpuInfo;
    /**
     * 內存相关信息
     */

    private String ramInfo;
    /**
     * JVM相关信息
     */
    private String fileInfo;

    public String getCpuInfo() {
        return cpuInfo;
    }

    public void setCpuInfo(String cpuInfo) {
        this.cpuInfo = cpuInfo;
    }

    public String getRamInfo() {
        return ramInfo;
    }

    public void setRamInfo(String ramInfo) {
        this.ramInfo = ramInfo;
    }

    public String getFileInfo() {
        return fileInfo;
    }

    public void setFileInfo(String fileInfo) {
        this.fileInfo = fileInfo;
    }

    @Override
    public String toString(){
       return getCpuInfo() + "----"+getRamInfo() +"----"+getFileInfo();
    }

}

4.控制器代码如下:

package com.gdhengdian.monitorservice.controller;
import com.gdhengdian.monitorservice.common.HttpRespond;
import com.gdhengdian.monitorservice.domain.SystemResourceInfo;
import com.gdhengdian.monitorservice.service.ServerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1/monitor")
public class MonitorController {

    @Autowired
    private ServerService serverService;

    @GetMapping("/system/info")
    public HttpRespond<SystemResourceInfo> getSystemInfo(){
        HttpRespond<SystemResourceInfo> respond = serverService.getSystemInfo();
        return respond;
    }
    
}

5.service代码如下:

package com.gdhengdian.monitorservice.service;
import com.gdhengdian.monitorservice.common.HttpRespond;

public interface ServerService {

    HttpRespond getSystemInfo();
}

实现类代码如下:

package com.gdhengdian.monitorservice.service.impl;


import com.gdhengdian.monitorservice.common.HttpRespond;
import com.gdhengdian.monitorservice.domain.Server;
import com.gdhengdian.monitorservice.domain.SystemResourceInfo;
import com.gdhengdian.monitorservice.service.ServerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class ServerServiceImpl implements ServerService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    Server server;
    @Autowired
    SystemResourceInfo systemResourceInfo;
    /*
    *  获取系统运行过程的系统数据
    */
    @Override
    public HttpRespond<SystemResourceInfo> getSystemInfo() {
        try {
            server.copyTo();
            systemResourceInfo.setCpuInfo(server.getCpu().getTotal());
            systemResourceInfo.setRamInfo(server.getMem().getUsedRate());
            systemResourceInfo.setFileInfo(server.getSysFiles().getUsage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        infoIntoRedis(systemResourceInfo);
        return  HttpRespond.success(systemResourceInfo);
    }
    
    /**
     * 将系统运行过程的信息放入Redis
     * @param systemResourceInfo
     */
    private void infoIntoRedis(SystemResourceInfo systemResourceInfo) {
        ValueOperations valueOperations = this.redisTemplate.opsForValue();
        valueOperations.set("systemsource", systemResourceInfo);
    }
}

这里接口返回的格式是使用了自己写的封装类HttpRespond,success方法就是将数据返回给前端页面,这里将所得到的数据存入了redis方便读取,你也可以按照你的业务逻辑进行数据处理。

相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页