首页>代码>SpringBoot+Maven+Echarts实现实时展示CPU内存硬盘性能>/system_performance/src/main/java/cn/temptation/web/IndexController.java
package cn.temptation.web; import org.hyperic.sigar.*; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.text.DecimalFormat; import java.util.*; @Controller public class IndexController { Sigar sigar = new Sigar(); @RequestMapping("/") public String index() { return "index"; } @RequestMapping("/getData") @ResponseBody public Map<String, String> getData() throws SigarException { DecimalFormat df = new DecimalFormat("#.##"); Map<String, String> map = new HashMap<>(); map.put("cpu", df.format(getCPUInfo())); map.put("memory", df.format(getMemoryInfo())); map.put("disk", df.format(getDiskInfo())); return map; } /** * 获取CPU利用率(多核CPU取的利用率最高的数据) * * @return * @throws SigarException */ private Double getCPUInfo() throws SigarException { ArrayList<Double> result = new ArrayList<>(); CpuInfo infos[] = sigar.getCpuInfoList(); CpuPerc cpuList[] = null; cpuList = sigar.getCpuPercList(); // 不管是单块CPU还是多CPU都适用 for (int i = 0; i < infos.length; i++) { result.add(cpuList[i].getSys() * 100); } return Collections.max(result); } /** * 获取内存利用率 * * @return * @throws SigarException */ private Double getMemoryInfo() throws SigarException { // 物理内存信息 Mem mem = sigar.getMem(); return mem.getUsed() * 100 / (double) mem.getTotal(); } /** * 获取内存利用率 * * @return * @throws SigarException */ private Double getDiskInfo() throws SigarException { FileSystem fslist[] = sigar.getFileSystemList(); long total = 0; long used = 0; for (int i = 0; i < fslist.length; i++) { FileSystem fs = fslist[i]; FileSystemUsage usage = sigar.getFileSystemUsage(fs.getDirName()); total += usage.getTotal(); used += usage.getUsed(); } return used * 100 / (double) total; } }