Java开发之道|系统监控-获取本机相关信息

java.util.Properties;



public class SystemUtil {
    public static void main(String[] args){
        Properties props=System.getProperties(); //获得系统属性集
        String osName = props.getProperty("os.name"); //操作系统名称
        System.out.println("osName:"+osName);
        String osArch = props.getProperty("os.arch"); //操作系统构架
        System.out.println("osArch:"+osArch);
        String osVersion = props.getProperty("os.version"); //操作系统版本
        System.out.println("osVersion:"+osVersion);
        SystemMonitor systemMonitor = new SystemMonitor();
        systemMonitor.init();
    }

    /*public static String getProperty(String key)    键 相关值的描述
      java.version    Java 运行时环境版本
      java.vendor     Java 运行时环境供应商
      java.vendor.url     Java 供应商的 URL
      java.home   Java 安装目录
      java.vm.specification.version   Java 虚拟机规范版本
      java.vm.specification.vendor    Java 虚拟机规范供应商
      java.vm.specification.name  Java 虚拟机规范名称
      java.vm.version     Java 虚拟机实现版本
      java.vm.vendor  Java 虚拟机实现供应商
      java.vm.name    Java 虚拟机实现名称
      java.specification.version  Java 运行时环境规范版本
      java.specification.vendor   Java 运行时环境规范供应商
      java.specification.name     Java 运行时环境规范名称
      java.class.version  Java 类格式版本号
      java.class.path     Java 类路径
      java.library.path   加载库时搜索的路径列表
      java.io.tmpdir  默认的临时文件路径
      java.compiler   要使用的 JIT 编译器的名称
      java.ext.dirs   一个或多个扩展目录的路径
      os.name     操作系统的名称
      os.arch     操作系统的架构
      os.version  操作系统的版本
      file.separator  文件分隔符(在 UNIX 系统中是“/”)
      path.separator  路径分隔符(在 UNIX 系统中是“:”)
      line.separator  行分隔符(在 UNIX 系统中是“/n”)
      user.name   用户的账户名称
      user.home   用户的主目录
      user.dir    用户的当前工作目录*/
}

添加依赖环境

<dependency>
    <groupId>com.github.oshi</groupId>
    <artifactId>oshi-core</artifactId>
    <version>3.12.2</version>
</dependency>
<dependency>
    <groupId>net.java.dev.jna</groupId>
    <artifactId>jna</artifactId>
    <version>5.5.0</version>
</dependency>
<dependency>
    <groupId>net.java.dev.jna</groupId>
    <artifactId>jna-platform</artifactId>
    <version>5.5.0</version>
</dependency>

public class SystemMonitor {
    public void init(){
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            try {
                SystemInfo systemInfo = new SystemInfo();
                OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
                MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
                // 椎内存使用情况                
                MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();
                // 初始的总内存               
                long initTotalMemorySize = memoryUsage.getInit();
                // 最大可用内存                
                long maxMemorySize = memoryUsage.getMax();
                // 已使用的内存               
                long usedMemorySize = memoryUsage.getUsed();
                // 操作系统                
                String osName = System.getProperty("os.name");
                // 总的物理内存                
                String totalMemorySize = new DecimalFormat("#.##")
                        .format(osmxb.getTotalPhysicalMemorySize() / 1024.0 / 1024 / 1024) + "G";
                // 剩余的物理内存               
                String freePhysicalMemorySize = new DecimalFormat("#.##")
                        .format(osmxb.getFreePhysicalMemorySize() / 1024.0 / 1024 / 1024) + "G";
                // 已使用的物理内存                
                String usedMemory = new DecimalFormat("#.##").format(
                        (osmxb.getTotalPhysicalMemorySize() - osmxb.getFreePhysicalMemorySize()) / 1024.0 / 1024 / 1024)
                        + "G";
                // 获得线程总数                
                ThreadGroup parentThread;
                for (parentThread = Thread.currentThread().getThreadGroup();
                     parentThread.getParent() != null;
                     parentThread = parentThread.getParent()) {
                }
                int totalThread = parentThread.activeCount();
                // 磁盘使用情况               
                File[] files = File.listRoots();
                for (File file : files) {
                    String total = new DecimalFormat("#.#").format(file.getTotalSpace() * 1.0 / 1024 / 1024 / 1024)
                            + "G";
                    String free = new DecimalFormat("#.#").format(file.getFreeSpace() * 1.0 / 1024 / 1024 / 1024) + "G";
                    String un = new DecimalFormat("#.#").format(file.getUsableSpace() * 1.0 / 1024 / 1024 / 1024) + "G";
                    String path = file.getPath();
                    System.err.println(path + "总:" + total + ",可用空间:" + un + ",空闲空间:" + free);
                    System.err.println("=============================================");
                }
                System.err.println("操作系统:" + osName);
                System.err.println("程序启动时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                        .format(new Date(ManagementFactory.getRuntimeMXBean().getStartTime())));
                System.err.println("pid:" + System.getProperty("PID"));
                System.err.println("cpu核数:" + Runtime.getRuntime().availableProcessors());
                printlnCpuInfo(systemInfo);
                System.err.println("JAVA_HOME:" + System.getProperty("java.home"));
                System.err.println("JAVA_VERSION:" + System.getProperty("java.version"));
                System.err.println("USER_HOME:" + System.getProperty("user.home"));
                System.err.println("USER_NAME:" + System.getProperty("user.name"));
                System.err.println("初始的总内存(JVM):"+ new DecimalFormat("#.#").format(initTotalMemorySize * 1.0 / 1024 / 1024) + "M");
                System.err.println("最大可用内存(JVM):" + new DecimalFormat("#.#").format(maxMemorySize * 1.0 / 1024 / 1024) + "M");
                System.err.println("已使用的内存(JVM):" + new DecimalFormat("#.#").format(usedMemorySize * 1.0 / 1024 / 1024) + "M");
                System.err.println("总的物理内存:" + totalMemorySize);
                System.err.println("总的物理内存:" + new DecimalFormat("#.##").format(
                        systemInfo.getHardware().getMemory().getTotal() * 1.0 / 1024 / 1024 / 1024)+ "M");
                System.err.println("剩余的物理内存:" + freePhysicalMemorySize);
                System.err.println("剩余的物理内存:"+ new DecimalFormat("#.##").format(
                        systemInfo.getHardware().getMemory().getAvailable() * 1.0 / 1024 / 1024 / 1024)+ "M");
                System.err.println("已使用的物理内存:" + usedMemory);
                System.err.println("已使用的物理内存:"+ new DecimalFormat("#.##").format((systemInfo.getHardware().getMemory().getTotal()
                        - systemInfo.getHardware().getMemory().getAvailable()) * 1.0 / 1024 / 1024 / 1024)+ "M");
                System.err.println("总线程数:" + totalThread);
                System.err.println("===========================");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, 0, 60, TimeUnit.SECONDS);    }

    /**     
     * 打印 CPU 信息    
     * @param systemInfo     
     */
    private void printlnCpuInfo(SystemInfo systemInfo) throws InterruptedException {
        CentralProcessor processor = systemInfo.getHardware().getProcessor();
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        // 睡眠1s        
        TimeUnit.SECONDS.sleep(1);
        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;
        System.err.println("cpu核数:" + processor.getLogicalProcessorCount());
        System.err.println("cpu系统使用率:" + new DecimalFormat("#.##%").format(cSys * 1.0 / totalCpu));
        System.err.println("cpu用户使用率:" + new DecimalFormat("#.##%").format(user * 1.0 / totalCpu));
        System.err.println("cpu当前等待率:" + new DecimalFormat("#.##%").format(iowait * 1.0 / totalCpu));
        System.err.println("cpu当前空闲率:" + new DecimalFormat("#.##%").format(idle * 1.0 / totalCpu));
        System.err.format("CPU load: %.1f%% (counting ticks)%n", processor.getSystemCpuLoadBetweenTicks() * 100);
        System.err.format("CPU load: %.1f%% (OS MXBean)%n", processor.getSystemCpuLoad() * 100);
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李景琰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值