获取服务器CPU、内存等各类信息工具类
  AnyLlCIhvKpr 2023年11月11日 55 0

1.引入jar包

1.1 Springboot2.3.0RELEASE以下版本

以下内容中的<!--$NO-MVN-MAN-VER$-->"不能省略

<!-- 19. 引入oshi依赖 -->
<dependency>
	<groupId>com.github.oshi</groupId>
	<artifactId>oshi-core</artifactId>
	<version>5.3.6</version>
</dependency>

<!-- 20. 引入jna依赖 -->
<dependency>
	<groupId>net.java.dev.jna</groupId>
	<artifactId>jna</artifactId>
	<version>5.6.0</version><!--$NO-MVN-MAN-VER$-->
</dependency>

<!-- 21. 引入jna-platform依赖 -->
<dependency>
	<groupId>net.java.dev.jna</groupId>
	<artifactId>jna-platform</artifactId>
	<version>5.6.0</version><!--$NO-MVN-MAN-VER$-->
</dependency>

1.2 Springboot2.3.0RELEASE及以上版本

<dependency>
	<groupId>com.github.oshi</groupId>
	<artifactId>oshi-core</artifactId>
	<version>5.3.6</version>
</dependency>

2.工具类

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 = "\\";

	public static void main(String[] args) {
		cpuInfo();
		getJvmInfo();
		getMemInfo();
		getSysFileInfo();
	}
	
	/**
	 * <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 void cpuInfo() {
        JSONObject cpuInfo = new JSONObject();
        
		SystemInfo systemInfo = new SystemInfo();
		// 获取硬件信息
		HardwareAbstractionLayer hardware = systemInfo.getHardware();
		// 获取处理器信息
        CentralProcessor processor = hardware.getProcessor();
        // 获取CPU信息
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        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("cpuNum-核数", processor.getLogicalProcessorCount());
        //cpu系统使用率
        cpuInfo.put("cSys-系统使用率", new DecimalFormat("#.##%").format(cSys * 1.0 / totalCpu));
        //cpu用户使用率
        cpuInfo.put("user-用户使用率", new DecimalFormat("#.##%").format(user * 1.0 / totalCpu));
        //cpu当前等待率
        cpuInfo.put("iowait-当前等待率", new DecimalFormat("#.##%").format(iowait * 1.0 / totalCpu));
        //cpu当前使用率
        cpuInfo.put("idle-当前使用率", new DecimalFormat("#.##%").format(1.0 - (idle * 1.0 / totalCpu)));
        
        System.out.println(cpuInfo.toJSONString());
	}
	
    /**
     * <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("total-jvm总内存", formatByte(runtime.totalMemory()));
        //空闲空间
        jvmInfo.put("free-空闲空间", formatByte(runtime.freeMemory()));
        //jvm最大可申请
        jvmInfo.put("max-jvm最大可申请", formatByte(runtime.maxMemory()));
        //vm已使用内存
        jvmInfo.put("user-vm已使用内存", formatByte(jvmTotalMemoryByte - freeMemoryByte));
        //jvm内存使用率
        jvmInfo.put("usageRate-jvm内存使用率", new DecimalFormat("#.##%").format((jvmTotalMemoryByte - freeMemoryByte) * 1.0 / jvmTotalMemoryByte));
        //jdk版本
        jvmInfo.put("jdkVersion-jdk版本", props.getProperty("java.version"));
        //jdk路径
        jvmInfo.put("jdkHome-jdk路径", props.getProperty("java.home"));
        
        System.out.println(jvmInfo.toJSONString());
        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("total-总内存", formatByte(totalByte));
        //已用内存
        memInfo.put("used-已用内存", formatByte(totalByte - acaliableByte));
        //剩余内存
        memInfo.put("free-剩余内存", formatByte(acaliableByte));
        //使用率
        memInfo.put("usageRate-使用率", new DecimalFormat("#.##%").format((totalByte - acaliableByte) * 1.0 / totalByte));
        
        System.out.println(memInfo.toJSONString());
        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("dirName-盘符路径", fs.getMount());
            //总大小
            sysFileInfo.put("total-总大小", formatByte(fs.getTotalSpace()));
            //剩余大小
            sysFileInfo.put("free-剩余大小", formatByte(fs.getUsableSpace()));
            //已经使用量
            sysFileInfo.put("used-已经使用量", formatByte(fs.getTotalSpace() - fs.getUsableSpace()));
            //盘符类型
            sysFileInfo.put("sysTypeName-盘符类型", fs.getType());
            //文件类型
            sysFileInfo.put("typeName-文件类型", fs.getName());
            if (fs.getTotalSpace() == 0) {
                //资源的使用率
                sysFileInfo.put("usage-资源的使用率", 0);
            } else {
                sysFileInfo.put("usage-资源的使用率",new DecimalFormat("#.##%").format((fs.getTotalSpace() - fs.getUsableSpace()) * 1.0 / fs.getTotalSpace()));
            }
            sysFiles.add(sysFileInfo);
            System.out.println(sysFileInfo.toJSONString());
        }
        
        return sysFiles;
    }
    
    // =================== private method ===================
    
    /**
     * 单位转换
     */
    private 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);
    }
}

如图:

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月11日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   30   0   0 服务器
  TEZNKK3IfmPf   2024年05月31日   52   0   0 linux服务器
  TEZNKK3IfmPf   2024年05月31日   30   0   0 linux服务器centos
  TEZNKK3IfmPf   2024年05月31日   28   0   0 JMM内存
  TEZNKK3IfmPf   2024年05月31日   43   0   0 服务器java
  TEZNKK3IfmPf   2024年05月31日   37   0   0 服务器http
AnyLlCIhvKpr