项目基于oshi库快速搭建一个cpu监控面板

在这里插入图片描述

后端:

      <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.github.oshi</groupId><artifactId>oshi-core</artifactId><version>5.8.5</version></dependency>
package org.example.cputest;import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.HardwareAbstractionLayer;import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;@CrossOrigin("*")
@RestController
@RequestMapping("/api/cpu")
public class CpuUsageController {private final SystemInfo systemInfo = new SystemInfo();private final HardwareAbstractionLayer hardware = systemInfo.getHardware();private final CentralProcessor processor = hardware.getProcessor();private long[][] prevTicks = processor.getProcessorCpuLoadTicks();@GetMapping("/usage")public String getCpuUsage() throws JsonProcessingException {// 获取当前的 tick 数long[][] ticks = processor.getProcessorCpuLoadTicks();// 获取 CPU 核心数int logicalProcessorCount = processor.getLogicalProcessorCount();// 计算每个核心的 CPU 使用率Map<String, Double> cpuUsages = new TreeMap<>(new Comparator<String>() {@Overridepublic int compare(String core1, String core2) {int num1 = Integer.parseInt(core1.replace("Core ", ""));int num2 = Integer.parseInt(core2.replace("Core ", ""));return Integer.compare(num1, num2);}});for (int i = 0; i < logicalProcessorCount; i++) {long user = ticks[i][CentralProcessor.TickType.USER.getIndex()] - prevTicks[i][CentralProcessor.TickType.USER.getIndex()];long nice = ticks[i][CentralProcessor.TickType.NICE.getIndex()] - prevTicks[i][CentralProcessor.TickType.NICE.getIndex()];long sys = ticks[i][CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[i][CentralProcessor.TickType.SYSTEM.getIndex()];long idle = ticks[i][CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[i][CentralProcessor.TickType.IDLE.getIndex()];long iowait = ticks[i][CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[i][CentralProcessor.TickType.IOWAIT.getIndex()];long irq = ticks[i][CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[i][CentralProcessor.TickType.IRQ.getIndex()];long softirq = ticks[i][CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[i][CentralProcessor.TickType.SOFTIRQ.getIndex()];long steal = ticks[i][CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[i][CentralProcessor.TickType.STEAL.getIndex()];long totalCpu = user + nice + sys + idle + iowait + irq + softirq + steal;// 检查 totalCpu 是否为零if (totalCpu == 0) {cpuUsages.put("Core " + i, 0.0);} else {double cpuUsage = (totalCpu - idle) * 100.0 / totalCpu;cpuUsages.put("Core " + i, cpuUsage);}}// 更新 prevTicksSystem.arraycopy(ticks, 0, prevTicks, 0, ticks.length);// 将结果转换为 JSON 字符串ObjectMapper objectMapper = new ObjectMapper();return objectMapper.writeValueAsString(cpuUsages);}
}

前端

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Dynamic CPU Performance Monitor 🖥️</title><!-- Vue and ECharts CDN --><script src="https://cdn.jsdelivr.net/npm/vue@2"></script><script src="https://cdn.jsdelivr.net/npm/echarts@5.3.2/dist/echarts.min.js"></script><style>body {font-family: Arial, sans-serif;background-color: #f0f0f0;text-align: center;}#app {display: flex;flex-wrap: wrap;justify-content: space-around;max-width: 1200px;margin: 0 auto;padding: 20px;}.chart-container {width: 300px;height: 350px;margin: 10px;background-color: white;border-radius: 10px;box-shadow: 0 4px 6px rgba(0,0,0,0.1);padding: 10px;position: relative;}.core-status {position: absolute;top: 10px;right: 10px;font-size: 24px;}h1 {color: #333;display: flex;align-items: center;justify-content: center;}h1 span {margin: 0 10px;}</style>
</head>
<body>
<h1><span>🖥️</span>CPU Performance Monitoring Dashboard<span>📊</span>
</h1>
<div id="app"><div v-for="(usage, core) in cpuUsageData" :key="core" class="chart-container"><div class="core-status"><span v-if="usage < 30">😎</span><span v-else-if="usage < 60">😓</span><span v-else-if="usage < 80">🥵</span><span v-else>🔥</span></div><div :ref="`chart-${core}`" style="width: 100%; height: 280px;"></div></div>
</div><script>// Create Vue instancenew Vue({el: '#app',data: {cpuUsageData: {},timeStamps: Array.from({length: 7}, () => 0)},mounted() {// Start timer to update data every secondthis.updateChart();},methods: {async updateChart() {try {// Fetch CPU usage dataconst response = await fetch('http://localhost:8080/api/cpu/usage');const data = await response.json();// Update CPU usage datathis.cpuUsageData = data;// Update timestampsthis.timeStamps.shift();this.timeStamps.push(new Date().toLocaleTimeString());// Iterate through each core, initialize or update EChartsObject.keys(this.cpuUsageData).forEach(core => {const usage = this.cpuUsageData[core];const chartContainer = this.$refs[`chart-${core}`][0];// Initialize chart if not existsif (!chartContainer.__chart) {chartContainer.__chart = echarts.init(chartContainer);chartContainer.__chart.setOption({title: {text: `Core ${core}`,left: 'center'},tooltip: {trigger: 'axis'},xAxis: {type: 'category',data: this.timeStamps},yAxis: {type: 'value',axisLabel: {formatter: '{value} %'},min: 0,max: 100},series: [{name: 'CPU Usage',type: 'line',smooth: true,  // 使线条平滑areaStyle: {color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{offset: 0, color: 'rgba(58,77,233,0.8)'},{offset: 1, color: 'rgba(58,77,233,0.3)'}])},data: Array.from({length: 7}, () => 0)}]});}// Update chart dataconst seriesData = chartContainer.__chart.getOption().series[0].data;seriesData.shift();seriesData.push(usage);chartContainer.__chart.setOption({xAxis: {data: this.timeStamps},series: [{data: seriesData}]});});} catch (error) {console.error('Error fetching CPU usage data:', error);}// Update every secondsetTimeout(this.updateChart, 1000);}}});
</script>
</body>
</html>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/888459.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【数据结构】手搓链表

一、定义 typedef struct node_s {int _data;struct node_s *_next; } node_t;typedef struct list_s {node_t *_head;node_t *_tail; } list_t;节点结构体&#xff08;node_s&#xff09;&#xff1a; int _data;存储节点中的数据struct node_s *_next;&#xff1a;指向 node…

毕设记录_音圈电机及电磁学相关_20241204

前言 提醒&#xff1a; 文章内容为方便作者自己后日复习与查阅而进行的书写与发布&#xff0c;其中引用内容都会使用链接表明出处&#xff08;如有侵权问题&#xff0c;请及时联系&#xff09;。 其中内容多为一次书写&#xff0c;缺少检查与订正&#xff0c;如有问题或其他拓展…

UPLOAD LABS | PASS 10 - 黑名单绕过(Windows . 绕过 - 变体)

关注这个靶场的其它相关笔记&#xff1a;UPLOAD LABS —— 靶场笔记合集-CSDN博客 0x01&#xff1a;过关流程 本关的目标是上传一个 WebShell 到目标服务器上&#xff0c;并成功访问&#xff1a; 通过查看源码&#xff0c;可以发现&#xff0c;本关在之前所有关卡的基础上做了…

【Elasticsearch】实现分布式系统日志高效追踪

&#x1f9d1; 博主简介&#xff1a;CSDN博客专家&#xff0c;历代文学网&#xff08;PC端可以访问&#xff1a;https://literature.sinhy.com/#/literature?__c1000&#xff0c;移动端可微信小程序搜索“历代文学”&#xff09;总架构师&#xff0c;15年工作经验&#xff0c;…

FoldX(FoldX5)的安装流程

下载地址:官网 https://foldxsuite.crg.eu/] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] zip解压yasaraPlugin.zip 我将foldx_20241231改为foldx vim ~/.bashrc 将foldx文件所在路径写进PATH vim ~/.bashrc我的…

利用红黑树封装map,和set,实现主要功能

如果不知道红黑树是什么的时候可以去看看这个红黑树 思路 首先我们可以把封装分为两个层面理解&#xff0c;上层代码就是set,和map&#xff0c;底层就是红黑树 就相当于根据红黑树上面套了两个map,set的壳子&#xff0c;像下面这张图一样 对于map和set&#xff0c;map里面存…

分类算法中的样本不平衡问题及其解决方案

一、样本不平衡问题概述 在机器学习的分类任务中&#xff0c;样本不平衡是指不同类别训练样本数量存在显著差异的现象。这一差异会给模型训练和性能评估带来挑战&#xff0c;尤其在处理少数类样本时&#xff0c;模型可能难以有效学习其特征。 以二分类为例&#xff0c;理想情况…

通过HTML Canvas 在图片上绘制文字

目录 前言 一、HTML Canvas 简介 二、准备工作 三、绘制图片 四、绘制文字 五、完整代码 效果演示&#xff1a; 前言 HTML canvas 为我们提供了无限的创意可能性。今天&#xff0c;我们就来探索一下如何通过 HTML canvas 将图片和文字绘制到图片上&#xff0c;创造出独特…

MBox20边缘计算网关:氢能车间数据采集的智慧引擎

氢能作为未来能源体系的重要组成部分&#xff0c;其安全、高效、环保的特性备受瞩目。在氢能车间的日常运营中&#xff0c;数据采集是确保生产流程优化、设备稳定运行及能效提升的关键环节。然而&#xff0c;面对氢能车间复杂多变的生产环境和海量数据&#xff0c;如何实现高效…

linux环境GitLab服务部署安装及使用

一、GitLab介绍 GitLab是利用Ruby onRails一个开源的版本管理系统&#xff0c;实现一个自托管的Git项目仓库&#xff0c;可通过Web界面进行访问公开的或者私人项目。 二、GitLab安装 1、先安装相关依赖 yum -y install policycoreutils openssh-server openssh-clients postf…

Gartner报告解读(四)| 如何运用上升期的基础设施自动化(IA)为企业数字化转型赋能?

近期&#xff0c;Gartner发布的《2024年中国基础设施战略技术成熟度曲线》显示&#xff0c;未来5-10年&#xff0c;大量具有颠覆性或较高影响力的创新技术可能会实现主流采用&#xff0c;其中就包括基础设施自动化&#xff08;IA&#xff09;。 基础设施自动化Gartner评估情况 …

请求响应:常见参数接收及封装(Json参数及路径参数)

Json参数 Json格式的数据具有轻量级、易于阅读和编写、易于解析等诸多优点。在前后端交互时&#xff0c;大部分情况下请求体中的数据会以JSON格式进行传递。前端的请求在请求体中携带了Json格式数据&#xff0c;后端程序需要对其进行解析并封装使用&#xff0c;而接收Json参数…

大舍传媒-关于海外媒体宣发的探讨

关于海外媒体宣发的探讨 一、海外媒体宣发的重要性 在当今全球化的时代&#xff0c;海外媒体宣发对于企业、组织和个人来说具有至关重要的意义。通过有效的海外媒体宣发&#xff0c;可以提升品牌知名度&#xff0c;拓展国际市场&#xff0c;增强影响力&#xff0c;吸引更多的潜…

项目开发之Jenkins

文章目录 思考基础概述JenkinsMavenGit集成开发部署GitLab服务 实战1 新建任务需要的配置pipeline最后 思考 jenkis怎么连接github仓库&#xff1f; jenkis的作用是什么&#xff1f;基础 概述 定义&#xff1a;Jenkins是一款开源的持续集成(Continuous Integration&#xff…

在VSCode中搭建Python开发环境

在VSCode中搭建Python开发环境 1、安装 首先确保电脑已经安装好Python和VSCode。 2、安装VSCode的Python插件 3、选择python解释器 ctrlshiftP打开VSCode的命令行&#xff0c;输入python: select Interpreter选择合适的python版本。 4、运行代码 在windows下你可以直接使用…

Windows 11 如何配置node.js

一&#xff0c;官网下载 官网首页 下载最新LTS版本&#xff0c;比较稳定&#xff0c;如果想探索更新的版本去探索新的nodejs功能。 1. 下载完成后&#xff0c;双击运行程序&#xff0c;点击next 2. 勾选接受协议&#xff0c;点击next 3. 选择自己的安装路径&#xff08;默认是…

1-12 GD32基于定时器输入捕获

前言&#xff1a; 基于本人对相关知识回顾与思考&#xff0c;仅供学习参考 目录 前言&#xff1a; 1.0 输入捕获 2.0 信号周期 3.0 定时器配置 4.0 定时器配置 5.0 定时器中断 后记&#xff1a; 1.0 输入捕获 2.0 信号周期 获取信号周期的方法&#xff0c;在第一次捕获与…

大数据新视界 -- Hive 元数据管理:核心元数据的深度解析(上)(27 / 30)

&#x1f496;&#x1f496;&#x1f496;亲爱的朋友们&#xff0c;热烈欢迎你们来到 青云交的博客&#xff01;能与你们在此邂逅&#xff0c;我满心欢喜&#xff0c;深感无比荣幸。在这个瞬息万变的时代&#xff0c;我们每个人都在苦苦追寻一处能让心灵安然栖息的港湾。而 我的…

合合信息智能图像处理技术,让你的设备更智能

目录 图像增强技术主要包括以下几个方面&#xff1a; 最近和一位朋友聊天&#xff0c;听到一些关于打印机的吐槽。 从20年开始&#xff0c;部分或者全部远程办公的企业渐渐多起来&#xff0c;wfh的打工人也在家添置了简易的必要办公设备&#xff0c;比如打印机。 在家用&…

基于Transformer的编码器-解码器图像描述模型在AMD GPU上的应用

Transformer based Encoder-Decoder models for image-captioning on AMD GPUs — ROCm Blogs 图像描述&#xff0c;即基于生成式人工智能&#xff08;GenAI&#xff09;自动生成简洁的图像文本描述&#xff0c;在现实世界中有着非常重要的应用。例如&#xff0c;图像描述可以为…