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

柔光的暖阳◎ 2023-01-10 15:56 973阅读 0赞

前言:

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

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

cpu相关信息实体

  1. package com.gdhengdian.monitorservice.domain.server;
  2. import org.springframework.stereotype.Component;
  3. import java.io.Serializable;
  4. /** * CPU相关信息 * * */
  5. @Component
  6. public class Cpu implements Serializable {
  7. /** * 核心数 */
  8. private int cpuNum;
  9. /** * CPU总的使用率 */
  10. private String total;
  11. /** * CPU系统使用率 */
  12. private String sys;
  13. /** * CPU用户使用率 */
  14. private String used;
  15. /** * CPU当前等待率 */
  16. private String wait;
  17. /** * CPU当前空闲率 */
  18. private String free;
  19. @Override
  20. public String toString() {
  21. return "Cpu{" +
  22. "核心数=" + getCpuNum() +
  23. ", CPU总的使用率=" + getTotal() +
  24. ", CPU系统使用率=" + getSys() +
  25. ", CPU用户使用率=" + getUsed() +
  26. ", CPU当前等待率=" + getWait() +
  27. ", CPU当前空闲率=" + getFree() +
  28. '}';
  29. }
  30. public int getCpuNum() {
  31. return cpuNum;
  32. }
  33. public void setCpuNum(int cpuNum) {
  34. this.cpuNum = cpuNum;
  35. }
  36. public String getTotal() {
  37. return total;
  38. }
  39. public void setTotal(String total) {
  40. this.total = total;
  41. }
  42. public String getSys() {
  43. return sys;
  44. }
  45. public void setSys(String sys) {
  46. this.sys = sys;
  47. }
  48. public String getUsed() {
  49. return used;
  50. }
  51. public void setUsed(String used) {
  52. this.used = used;
  53. }
  54. public String getWait() {
  55. return wait;
  56. }
  57. public void setWait(String wait) {
  58. this.wait = wait;
  59. }
  60. public String getFree() {
  61. return free;
  62. }
  63. public void setFree(String free) {
  64. this.free = free;
  65. }
  66. }

内存相关信息实体:

  1. package com.gdhengdian.monitorservice.domain.server;
  2. import org.springframework.stereotype.Component;
  3. import java.io.Serializable;
  4. /** * 內存相关信息 * * @author ruoyi */
  5. @Component
  6. public class Mem implements Serializable {
  7. private String usedRate;
  8. /** * 内存总量 */
  9. private long total;
  10. /** * 已用内存 */
  11. private long used;
  12. /** * 剩余内存 */
  13. private long free;
  14. @Override
  15. public String toString() {
  16. return "Mem{" +
  17. "内存总量=" + getTotal() +
  18. ",同上=" + getUsed() +
  19. ", 剩余内存=" + getFree() +
  20. ", 使用率="+ getUsedRate() +
  21. '}';
  22. }
  23. public double getTotal()
  24. {
  25. return Arith.div(total, (1024 * 1024 * 1024), 2);
  26. }
  27. public void setTotal(long total)
  28. {
  29. this.total = total;
  30. }
  31. public double getUsed()
  32. {
  33. return Arith.div(used, (1024 * 1024 * 1024), 2);
  34. }
  35. public void setUsed(long used)
  36. {
  37. this.used = used;
  38. }
  39. public double getFree()
  40. {
  41. return Arith.div(free, (1024 * 1024 * 1024), 2);
  42. }
  43. public void setFree(long free)
  44. {
  45. this.free = free;
  46. }
  47. public double getUsage()
  48. {
  49. return Arith.mul(Arith.div(used, total, 4), 100);
  50. }
  51. public String getUsedRate() {
  52. return usedRate;
  53. }
  54. public void setUsedRate(String usedRate) {
  55. this.usedRate = usedRate;
  56. }
  57. }

磁盘相关信息实体

  1. package com.gdhengdian.monitorservice.domain.server;
  2. import org.springframework.stereotype.Component;
  3. import java.io.Serializable;
  4. /** * 系统文件相关信息 * */
  5. @Component
  6. public class SysFile implements Serializable {
  7. /** * 盘符路径 */
  8. private String dirName;
  9. /** * 盘符类型 */
  10. private String sysTypeName;
  11. /** * 文件类型 */
  12. private String typeName;
  13. /** * 总大小 */
  14. private String total;
  15. /** * 剩余大小 */
  16. private String free;
  17. /** * 已经使用量 */
  18. private String used;
  19. /** * 资源的使用率 */
  20. private String usage;
  21. @Override
  22. public String toString() {
  23. return "SysFile{" +
  24. "盘符路径='" + getDirName() + '\'' +
  25. ", 盘符类型='" + getSysTypeName() + '\'' +
  26. ", 文件类型='" + getTypeName() + '\'' +
  27. ", 总大小='" + getTotal() + '\'' +
  28. ", 剩余大小='" + getFree()+ '\'' +
  29. ", 已经使用量='" + getUsed() + '\'' +
  30. ", 资源的使用率=" + getUsage() +
  31. '}';
  32. }
  33. public String getDirName()
  34. {
  35. return dirName;
  36. }
  37. public void setDirName(String dirName)
  38. {
  39. this.dirName = dirName;
  40. }
  41. public String getSysTypeName()
  42. {
  43. return sysTypeName;
  44. }
  45. public void setSysTypeName(String sysTypeName)
  46. {
  47. this.sysTypeName = sysTypeName;
  48. }
  49. public String getTypeName()
  50. {
  51. return typeName;
  52. }
  53. public void setTypeName(String typeName)
  54. {
  55. this.typeName = typeName;
  56. }
  57. public String getTotal()
  58. {
  59. return total;
  60. }
  61. public void setTotal(String total)
  62. {
  63. this.total = total;
  64. }
  65. public String getFree()
  66. {
  67. return free;
  68. }
  69. public void setFree(String free)
  70. {
  71. this.free = free;
  72. }
  73. public String getUsed()
  74. {
  75. return used;
  76. }
  77. public void setUsed(String used)
  78. {
  79. this.used = used;
  80. }
  81. public String getUsage()
  82. {
  83. return usage;
  84. }
  85. public void setUsage(String usage)
  86. {
  87. this.usage = usage;
  88. }
  89. }

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

  1. package com.gdhengdian.monitorservice.domain;
  2. import com.gdhengdian.monitorservice.domain.server.Arith;
  3. import com.gdhengdian.monitorservice.domain.server.Cpu;
  4. import com.gdhengdian.monitorservice.domain.server.Mem;
  5. import com.gdhengdian.monitorservice.domain.server.SysFile;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Component;
  8. import oshi.SystemInfo;
  9. import oshi.hardware.CentralProcessor;
  10. import oshi.hardware.GlobalMemory;
  11. import oshi.hardware.HardwareAbstractionLayer;
  12. import oshi.software.os.FileSystem;
  13. import oshi.software.os.OSFileStore;
  14. import oshi.software.os.OperatingSystem;
  15. import oshi.util.Util;
  16. import oshi.hardware.CentralProcessor.TickType;
  17. import java.text.NumberFormat;
  18. /** * 服务器相关信息 * */
  19. @Component
  20. public class Server
  21. {
  22. private static final int OSHI_WAIT_SECOND = 2000;
  23. /** * CPU相关信息 */
  24. @Autowired
  25. private Cpu cpu;
  26. /** * 內存相关信息 */
  27. @Autowired
  28. private Mem mem;
  29. /** * 磁盘相关信息 */
  30. @Autowired
  31. private SysFile sysFiles;
  32. /** * 获取磁盘,CPU,运行内存等数据 * @throws Exception */
  33. public void copyTo() throws Exception
  34. {
  35. SystemInfo si = new SystemInfo();
  36. HardwareAbstractionLayer hal = si.getHardware();
  37. //cpux信息
  38. setCpuInfo(hal.getProcessor());
  39. //内存信息
  40. setMemInfo(hal.getMemory());
  41. //磁盘信息
  42. setSysFiles(si.getOperatingSystem());
  43. }
  44. /** * 设置CPU信息 */
  45. private void setCpuInfo(CentralProcessor processor)
  46. {
  47. // CPU信息
  48. long[] prevTicks = processor.getSystemCpuLoadTicks();//cpu时钟1的计算出来的cpu各项指标(单位:节拍数)
  49. Util.sleep(OSHI_WAIT_SECOND);
  50. long[] ticks = processor.getSystemCpuLoadTicks(); //cpu时钟2的计算出来的cpu各项值(单位:节拍数)
  51. //以高优先级在用户级别执行时发生的CPU节拍数。
  52. Long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
  53. //CPU中断花销的节拍
  54. Long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
  55. //软中断花销的节拍
  56. Long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
  57. //系统监控程序为其它用户开启的cpu节拍,Only supported on Linux.
  58. Long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
  59. //CPU在内核空间运行的节拍花销
  60. Long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
  61. //用户进程对CPU的节拍花销
  62. Long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
  63. //CPU调用IO操作的节拍花销
  64. Long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
  65. //CPU处于空闲状态节拍花销
  66. Long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
  67. Long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
  68. Long cpuUsed = (cSys + user);
  69. double usedRate = cpuUsed.doubleValue() / totalCpu.doubleValue();
  70. // 创建一个数值格式化对象
  71. NumberFormat numberFormat = NumberFormat.getInstance();
  72. // 设置精确到小数点后2位
  73. numberFormat.setMaximumFractionDigits(2);
  74. String totalRate = numberFormat.format( usedRate * 100) ;//所占百分比
  75. cpu.setCpuNum(processor.getLogicalProcessorCount());
  76. cpu.setTotal(totalRate);
  77. }
  78. /** * 设置内存信息 */
  79. private void setMemInfo(GlobalMemory memory) {
  80. long totalMem = memory.getTotal();
  81. mem.setTotal(totalMem);
  82. mem.setUsed(memory.getTotal() - memory.getAvailable());
  83. mem.setFree(memory.getAvailable());
  84. // 创建一个数值格式化对象
  85. NumberFormat numberFormat = NumberFormat.getInstance();
  86. // 设置精确到小数点后2位
  87. numberFormat.setMaximumFractionDigits(2);
  88. String usedRate = numberFormat.format(mem.getUsed() / mem.getTotal() * 100);//所占百分比
  89. mem.setUsedRate(usedRate);
  90. }
  91. /** * 设置磁盘信息 */
  92. private void setSysFiles(OperatingSystem os)
  93. {
  94. FileSystem fileSystem = os.getFileSystem();
  95. OSFileStore[] fsArray = fileSystem.getFileStores();
  96. long total = 0;
  97. long used = 0;
  98. long free = 0;
  99. for (OSFileStore fs : fsArray)
  100. {
  101. free += fs.getUsableSpace();
  102. total += fs.getTotalSpace();
  103. }
  104. used = total - free;
  105. double rate = Arith.mul(Arith.div(used, total, 4), 100);
  106. sysFiles.setUsage(new StringBuffer().append(rate).toString());
  107. }
  108. @Override
  109. public String toString() {
  110. return "Server{" +
  111. "cpu=" + getCpu() +
  112. "\n, memory=" + getMem() +
  113. ",\n sysFiles=" + getSysFiles() +
  114. '}';
  115. }
  116. public Cpu getCpu() {
  117. return cpu;
  118. }
  119. public void setCpu(Cpu cpu) {
  120. this.cpu = cpu;
  121. }
  122. public Mem getMem() {
  123. return mem;
  124. }
  125. public void setMem(Mem mem) {
  126. this.mem = mem;
  127. }
  128. public SysFile getSysFiles() {
  129. return sysFiles;
  130. }
  131. public void setSysFiles(SysFile sysFiles) {
  132. this.sysFiles = sysFiles;
  133. }
  134. }

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

  1. package com.gdhengdian.monitorservice.domain;
  2. import org.springframework.stereotype.Component;
  3. import java.io.Serializable;
  4. @Component
  5. public class SystemResourceInfo implements Serializable {
  6. /** * CPU相关信息 */
  7. private String cpuInfo;
  8. /** * 內存相关信息 */
  9. private String ramInfo;
  10. /** * JVM相关信息 */
  11. private String fileInfo;
  12. public String getCpuInfo() {
  13. return cpuInfo;
  14. }
  15. public void setCpuInfo(String cpuInfo) {
  16. this.cpuInfo = cpuInfo;
  17. }
  18. public String getRamInfo() {
  19. return ramInfo;
  20. }
  21. public void setRamInfo(String ramInfo) {
  22. this.ramInfo = ramInfo;
  23. }
  24. public String getFileInfo() {
  25. return fileInfo;
  26. }
  27. public void setFileInfo(String fileInfo) {
  28. this.fileInfo = fileInfo;
  29. }
  30. @Override
  31. public String toString(){
  32. return getCpuInfo() + "----"+getRamInfo() +"----"+getFileInfo();
  33. }
  34. }

4.控制器代码如下:

  1. package com.gdhengdian.monitorservice.controller;
  2. import com.gdhengdian.monitorservice.common.HttpRespond;
  3. import com.gdhengdian.monitorservice.domain.SystemResourceInfo;
  4. import com.gdhengdian.monitorservice.service.ServerService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.web.bind.annotation.GetMapping;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RestController;
  9. @RestController
  10. @RequestMapping("/api/v1/monitor")
  11. public class MonitorController {
  12. @Autowired
  13. private ServerService serverService;
  14. @GetMapping("/system/info")
  15. public HttpRespond<SystemResourceInfo> getSystemInfo(){
  16. HttpRespond<SystemResourceInfo> respond = serverService.getSystemInfo();
  17. return respond;
  18. }
  19. }

5.service代码如下:

  1. package com.gdhengdian.monitorservice.service;
  2. import com.gdhengdian.monitorservice.common.HttpRespond;
  3. public interface ServerService {
  4. HttpRespond getSystemInfo();
  5. }

实现类代码如下:

  1. package com.gdhengdian.monitorservice.service.impl;
  2. import com.gdhengdian.monitorservice.common.HttpRespond;
  3. import com.gdhengdian.monitorservice.domain.Server;
  4. import com.gdhengdian.monitorservice.domain.SystemResourceInfo;
  5. import com.gdhengdian.monitorservice.service.ServerService;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.data.redis.core.RedisTemplate;
  8. import org.springframework.data.redis.core.ValueOperations;
  9. import org.springframework.stereotype.Service;
  10. @Service
  11. public class ServerServiceImpl implements ServerService {
  12. @Autowired
  13. private RedisTemplate<String, Object> redisTemplate;
  14. @Autowired
  15. Server server;
  16. @Autowired
  17. SystemResourceInfo systemResourceInfo;
  18. /* * 获取系统运行过程的系统数据 */
  19. @Override
  20. public HttpRespond<SystemResourceInfo> getSystemInfo() {
  21. try {
  22. server.copyTo();
  23. systemResourceInfo.setCpuInfo(server.getCpu().getTotal());
  24. systemResourceInfo.setRamInfo(server.getMem().getUsedRate());
  25. systemResourceInfo.setFileInfo(server.getSysFiles().getUsage());
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. }
  29. infoIntoRedis(systemResourceInfo);
  30. return HttpRespond.success(systemResourceInfo);
  31. }
  32. /** * 将系统运行过程的信息放入Redis * @param systemResourceInfo */
  33. private void infoIntoRedis(SystemResourceInfo systemResourceInfo) {
  34. ValueOperations valueOperations = this.redisTemplate.opsForValue();
  35. valueOperations.set("systemsource", systemResourceInfo);
  36. }
  37. }

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

发表评论

表情:
评论列表 (有 0 条评论,973人围观)

还没有评论,来说两句吧...

相关阅读