天天看點

java監控JVM的記憶體使用情況等

     以下的程式監控參數的代碼,有些是從網絡上擷取的,此處進行一個記錄是為了以後如果要用到友善記錄。

1、引入jar包,為了擷取一些cpu的使用率等資訊

<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.2.0</version>

</dependency>

<dependency>

<groupId>net.java.dev.jna</groupId>

<artifactId>jna-platform</artifactId>

<version>5.2.0</version>

</dependency>

2、編寫代碼

/**
 * 系統監控
 *
 * @author huan.fu
 * @date 2018/12/3 - 18:44
 */
@Component
public class SystemMonitor {

  @PostConstruct
  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);
  }
}      

3、擷取更多系統資訊,參考如下網址

​​ https://github.com/oshi/oshi​​