如何用Rust获取本机CPU、内存在Web网页中显示?

目录

一、需求描述

二、具体操作步骤

三、知识点

1、systemstat

2、Actix 


一、需求描述

需求:

1、需要使用Rust进行后端开发获取本机CPU和内存信息;

2、使用WEB框架发布API;

3、然后使用HTML/CSS/JavaScript进行前端开发,显示结果;

以下是一个简单的示例,展示了如何获取系统信息并使用Actix-Web提供API,然后在前端使用JavaScript来实时刷新数据。

二、具体操作步骤

修改Cargo.toml,添加用到的依赖

[dependencies]
systemstat = "0.2.3"
actix-web = "3.3.2"

PS E:\RustroverProjects> cargo add systemstat

    Updating crates.io index

      Adding systemstat v0.2.3 to dependencies                                                                                                                                     

             Features:

             - serde

             - the_serde

    Updating crates.io index

PS E:\RustroverProjects> cargo add actix-web 

    Blocking waiting for file lock on package cache

    Updating crates.io index

      Adding actix-web v3.3.2 to dependencies                                                                                                                                      

             Features:

             + compress

             - open-ssl

             - openssl

             - rust-tls

             - rustls

             - secure-cookies 

             - secure-cookies

 

 代码如下:

use std::thread;
use std::time::Duration;
use systemstat::{System, Platform, saturating_sub_bytes};
use actix_web::{get, web, App, HttpResponse, HttpServer, Responder};
async fn sys_info() -> String {
    let sys = System::new();
    let mut cpu_info = String::new();
    let mut memory_info = String::new();
    match sys.cpu_load_aggregate() {
        Ok(cpu)=> {
            println!("\nMeasuring CPU load...");
            thread::sleep(Duration::from_secs(1));
            let cpu = cpu.done().unwrap();
            println!("\nCPU load: {}% user, {}% nice, {}% system, {}% intr, {}% idle ",
                     cpu.user * 100.0, cpu.nice * 100.0, cpu.system * 100.0, cpu.interrupt * 100.0, cpu.idle * 100.0);
            cpu_info = format!("\nCPU load: {}% user, {}% nice, {}% system, {}% intr, {}% idle ",cpu.user * 100.0, cpu.nice * 100.0, cpu.system * 100.0, cpu.interrupt * 100.0, cpu.idle * 100.0);
        },
        Err(x) => println!("\nCPU load: error: {}", x)
    }
    match sys.memory() {
        Ok(mem) => {
            println!("\nMemory: {} used / {} ({} bytes) total ({:?})", saturating_sub_bytes(mem.total, mem.free), mem.total, mem.total.as_u64(), mem.platform_memory);
            memory_info = format!("\nMemory: {} used / {} ({} bytes) total ({:?})", saturating_sub_bytes(mem.total, mem.free), mem.total, mem.total.as_u64(), mem.platform_memory);
        },
        Err(x) => println!("\nMemory: error: {}", x)
    }
    format!("CPU: {}\nMemory: {}", cpu_info,memory_info)
}
#[get("/")]
async fn hello() -> impl Responder {
    HttpResponse::Ok().body("Hello world!")
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(hello)
            .route("/api", web::get().to(sys_info))
    })
        .bind(("127.0.0.1", 8080))?
        .run()
        .await
}

运行结果如下:  

三、知识点

1、systemstat

This library provides a way to access system information such as CPU load, mounted filesystems, network interfaces, etc.

该库提供了一种访问系统信息的方法,如CPU负载、已安装的文件系统、网络接口等。

systemstat - RustThis library provides a way to access system information such as CPU load, mounted filesystems, network interfaces, etc.icon-default.png?t=N7T8https://docs.rs/systemstat/latest/systemstat/index.html

2、Actix 

Actix Web lets you quickly and confidently develop web services in Rust and this guide will get you going in no time.

Actix Web可以让您快速而自信地在Rust中开发Web服务,本指南将很快让您上手。

Getting Started | ActixInstalling Rusticon-default.png?t=N7T8https://actix.rs/docs/getting-started