本项目是一个极简的资源占用显示系统,严格按照 templates/index.html 设计,专为嵌入式设备监控场景设计。系统支持 200+ 高并发客户端访问,数据更新后 10 秒算过期,无 CSS 无 JS,采用服务器端渲染确保最简实现。
graph TB
A[客户端浏览器] --> B[HTTP 服务器]
B --> C[HTML 渲染器]
C --> D[无锁缓存系统]
D --> E[系统资源获取器]
E --> F[Linux /proc 文件系统]
| 组件 | 选择理由 | 替代方案 |
|---|---|---|
| 核心语言 | Rust:内存安全、零成本抽象、优秀并发支持 | Go、C++ |
| Web 框架 | tokio + hyper:最小依赖、高性能 | actix-web、rocket |
| 异步运行时 | tokio:成熟的异步生态 | async-std |
| 系统调用 | 直接读取 /proc:零依赖、高性能 | sysinfo crate |
| 模板引擎 | 简单字符串格式化:无额外依赖 | handlebars、tera |
#[derive(Debug, Clone)]
pub struct SystemStats {
pub hostname: String,
pub cpu_usage: f32, // CPU 使用率 (0.0-1.0)
pub memory_total: u64, // 总内存字节数
pub memory_used: u64, // 已用内存字节数
pub memory_available: u64, // 可用内存字节数
pub memory_cached: u64, // 缓存内存字节数
pub memory_free: u64, // 空闲内存字节数
pub timestamp: Instant, // 数据获取时间戳
}
Linux 优化路径:
/proc/stat,计算使用率/proc/meminfo,获取详细信息/proc/sys/kernel/hostname跨平台支持:
#[cfg(target_os = "linux")]
fn collect_linux_stats() -> Result<SystemStats>
#[cfg(target_os = "windows")]
fn collect_windows_stats() -> Result<SystemStats>
#[cfg(target_os = "macos")]
fn collect_macos_stats() -> Result<SystemStats>
性能优化:
use arc_swap::ArcSwap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
pub struct SystemStatsCache {
current_stats: ArcSwap<SystemStats>,
last_update: AtomicU64,
ttl: Duration,
}
impl SystemStatsCache {
pub fn new(ttl: Duration) -> Self {
Self {
current_stats: ArcSwap::from_pointee(SystemStats::default()),
last_update: AtomicU64::new(0),
ttl,
}
}
// 无锁读取
pub fn get(&self) -> Option<Arc<SystemStats>> {
let last_update = self.last_update.load(Ordering::Acquire);
if last_update == 0 {
return None; // 未初始化
}
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis() as u64;
// saturating_sub 防止时钟回拨导致整数下溢
if now.saturating_sub(last_update) > self.ttl.as_millis() as u64 {
return None; // 数据过期
}
Some(self.current_stats.load_full())
}
// 原子更新
pub fn update(&self, new_stats: SystemStats) {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis() as u64;
// 原子替换数据(旧值由 Arc 引用计数自动释放)
self.current_stats.store(Arc::new(new_stats));
// 最后更新时间戳,确保数据先于时间戳可见
self.last_update.store(now, Ordering::Release);
}
}
按需更新策略:
// 只有在数据过期且有请求时才更新
pub async fn get_or_update(&self) -> Result<SystemStats> {
// 先尝试获取缓存
if let Some(stats) = self.get() {
return Ok(stats);
}
// 数据过期或不存在,重新获取
let new_stats = collect_system_stats().await?;
self.update(new_stats.clone());
Ok(new_stats)
}
惰性更新模式:
use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};
use std::convert::Infallible;
use std::sync::Arc;
pub struct StatusServer {
cache: Arc<SystemStatsCache>,
}
impl StatusServer {
pub async fn new(cache: Arc<SystemStatsCache>) -> Result<Self> {
Ok(Self { cache })
}
pub async fn run(self, addr: SocketAddr) -> Result<()> {
let cache = self.cache;
let make_svc = make_service_fn(move |_conn| {
let cache = cache.clone();
async move {
Ok::<_, Infallible>(service_fn(move |req| {
let cache = cache.clone();
Self::handle_request(req, cache)
}))
}
});
let server = Server::bind(&addr).serve(make_svc);
println!("服务器运行在: http://{}", addr);
if let Err(e) = server.await {
eprintln!("服务器错误: {}", e);
}
Ok(())
}
async fn handle_request(
req: Request<Body>,
cache: Arc<SystemStatsCache>,
) -> Result<Response<Body>, Infallible> {
match (req.method(), req.uri().path()) {
(&Method::GET, "/") => Self::serve_html(req, cache).await,
_ => Self::serve_404(),
}
}
}
连接处理:
Arc 共享只读数据HTTP 优化:
严格按照 templates/index.html 设计,无 CSS,无 JS,使用 HTML 自动刷新机制。
由于无 JavaScript,采用服务器端直接渲染 HTML:
impl StatusServer {
async fn serve_html(&self, req: Request<Body>) -> Result<Response<Body>, Infallible> {
// 获取系统数据
let stats = match self.cache.get_or_update().await {
Ok(stats) => stats,
Err(_) => {
return Ok(Response::builder()
.status(500)
.body(Body::from("数据获取失败"))
.unwrap());
}
};
// 渲染 HTML 模板
let html = self.render_html_template(&stats);
Ok(Response::builder()
.header("content-type", "text/html; charset=utf-8")
.body(Body::from(html))
.unwrap())
}
fn render_html_template(&self, stats: &SystemStats) -> String {
let total_mb = stats.memory_total / 1024 / 1024;
let used_mb = stats.memory_used / 1024 / 1024;
let available_mb = stats.memory_available / 1024 / 1024;
let cached_mb = stats.memory_cached / 1024 / 1024;
let free_mb = stats.memory_free / 1024 / 1024;
let cpu_percent = (stats.cpu_usage * 100.0) as u32;
format!(
include_str!("../templates/index.html"),
hostname = stats.hostname,
cpu_percent = cpu_percent,
memory_total_mb = total_mb,
memory_used_mb = used_mb,
memory_available_mb = available_mb,
memory_cached_mb = cached_mb,
memory_free_mb = free_mb
timestamp = stats.timestamp
)
}
}
零拷贝设计:
Cow<str> 减少分配内存池管理:
SystemStats 对象Vec::with_capacity() 预分配容量栈分配优先:
#[inline] 优化小函数计算优化:
I/O 优化:
mio 直接操作 epoll/kqueue并发优化:
协议优化:
数据压缩:
[profile.release]
lto = true # 链接时优化
codegen-units = 1 # 减少代码生成单元
panic = "abort" # 减少二进制大小
strip = true # 移除调试符号
#[derive(Debug, Clone)]
pub struct Config {
pub bind_address: String,
pub port: u16,
pub cache_ttl: Duration,
pub update_interval: Duration,
pub max_connections: usize,
}
impl Default for Config {
fn default() -> Self {
Self {
bind_address: "0.0.0.0".to_string(),
port: 8080,
cache_ttl: Duration::from_secs(10), // 严格 10 秒过期
update_interval: Duration::from_secs(10), // 无后台定时更新
max_connections: 1000,
}
}
}
[Unit]
Description=Resource Status Monitor
After=network.target
[Service]
Type=simple
User=nobody
ExecStart=/usr/local/bin/swb-status-page
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
本设计文档详细描述了资源占用显示系统的技术架构和实现方案。系统采用 Rust 语言,严格按照 templates/index.html 设计,无 CSS 无 JS,结合无锁算法和按需更新策略,实现了极简、高性能的监控解决方案。通过服务器端渲染和 10 秒数据过期机制,系统能够在嵌入式设备上稳定运行,支持 200+ 并发客户端访问,同时确保数据未过期时无须再次获取,无用户访问时无须获取。