赞
踩
目录
需求:
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 indexPS 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
- }
运行结果如下:
This library provides a way to access system information such as CPU load, mounted filesystems, network interfaces, etc.
该库提供了一种访问系统信息的方法,如CPU负载、已安装的文件系统、网络接口等。
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 Rusthttps://actix.rs/docs/getting-started
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。