Rust中的缓存:Redis及其他加速应用程序的工具
缓存是优化性能的关键机制之一。在注重速度和安全性的Rust中,选择合适的缓存工具可以带来显著的性能提升。本文将介绍流行的库:redis-rs(带连接池)、moka(内存缓存)和cached(函数装饰器)。
1. Redis:通过redis-rs和deadpool实现的外部缓存
Redis 是最常见的外部缓存。在Rust中,使用 redis-rs crate 进行操作。对于生产环境负载,建议通过 deadpool-redis 连接连接池。
安装
[dependencies]redis = { version = "0.25", features = ["tokio-comp"] }deadpool-redis = "0.14"tokio = { version = "1", features = ["full"] }serde = { version = "1", features = ["derive"] }serde_json = "1"示例:Redis基本操作
use redis::AsyncCommands;use deadpool_redis::{Config, Runtime};
#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error>> { // 创建连接池 let cfg = Config::from_url("redis://127.0.0.1:6379"); let pool = cfg.create_pool(Some(Runtime::Tokio1))?;
// 从连接池获取连接 let mut conn = pool.get().await?;
// 设置带60秒TTL的值 conn.set_ex("user:42", "{\\"name\\":\\"Alice\\",\\"role\\":\\"admin\\"}", 60).await?;
// 读取 let value: String = conn.get("user:42").await?; println!("获取到: {}", value);
// 删除 conn.del("user:42").await?;
Ok(())}结构体序列化
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug)]struct User { id: u64, name: String, email: String,}
async fn cache_user(conn: &mut redis::aio::Connection, user: &User) -> redis::RedisResult<()> { let key = format!("user:{}", user.id); let json = serde_json::to_string(user).unwrap(); conn.set_ex(key, json, 300).await}
async fn get_cached_user(conn: &mut redis::aio::Connection, id: u64) -> Option<User> { let key = format!("user:{}", id); let result: Option<String> = conn.get(key).await.ok()?; result.and_then(|json| serde_json::from_str(&json).ok())}2. Moka:快速的内存缓存
Moka 是一个高性能的内存缓存,灵感来源于Caffeine(Java)。支持TTL、大小限制和异步更新。
安装
[dependencies]moka = { version = "0.12", features = ["future"] }tokio = { version = "1", features = ["full"] }示例:限制1000个元素且TTL为10分钟的缓存
use moka::future::Cache;use std::time::Duration;
#[tokio::main]async fn main() { let cache: Cache<String, String> = Cache::builder() .max_capacity(1000) .time_to_live(Duration::from_secs(600)) .build();
// 插入 cache.insert("key1".to_string(), "value1".to_string()).await;
// 读取 if let Some(v) = cache.get(&"key1".to_string()).await { println!("找到: {}", v); }
// 删除 cache.invalidate(&"key1".to_string()).await;}TTL过期后自动更新
let cache: Cache<String, String> = Cache::builder() .time_to_live(Duration::from_secs(60)) .time_to_idle(Duration::from_secs(30)) // 读取时重置TTL .build();3. Cached:函数装饰器
cached crate 允许通过属性缓存函数结果。支持多种后端,包括Redis和内存缓存。
安装
[dependencies]cach