Rust在写库时实现缓存

Rust在写库时实现缓存

依赖

在写库时,实现一个缓存请求,需要用到全局变量,所以我们可以添加cratelazy_static

Cargo.toml添加以下依赖

toml 复制代码
[dependencies]
chrono = "0.4.31"
lazy_static = "1.4.0"
reqwest = { version = "0.11.23", features = ["blocking", "json"] }
serde = { version = "1.0.193", features = ["derive"] }
serde_json = "1.0.108"

代码实现

rust 复制代码
use std::{sync::Mutex, collections::HashMap};

use chrono::{DateTime, Utc};
use lazy_static::lazy_static;
use serde_json::Value;

lazy_static! {
    static ref REQUESTS_RESPONSE_CACHE: Mutex<HashMap<String, RequestsResponseCache>> =
        Mutex::new(HashMap::new());
}

pub struct RequestsResponseCache {
    pub response: Value,
    pub datetime: DateTime<Utc>,
}

pub fn get_requests_response_cache(url: &str) -> Result<Value, reqwest::Error> {
    let mut cache = REQUESTS_RESPONSE_CACHE.lock().unwrap();
    if let Some(cache_entry) = cache.get(url) {
        let elapsed = Utc::now() - cache_entry.datetime;
        if elapsed.num_seconds() > 3600 {
            let response: Value = reqwest::blocking::get(url)?.json()?;
            let res = response.clone();
            let cache_entry = RequestsResponseCache {
                response,
                datetime: Utc::now(),
            };
            cache.insert(url.to_string(), cache_entry);
            return Ok(res);
        }
    }

    let response: Value = reqwest::blocking::get(url)?.json()?;
    let res = response.clone();
    let cache_entry = RequestsResponseCache {
        response,
        datetime: Utc::now(),
    };
    cache.insert(url.to_string(), cache_entry);
    Ok(res)
}

使用了 lazy_static 宏创建了一个静态的全局变量 REQUESTS_RESPONSE_CACHE,这个全局变量是一个 Mutex 包裹的 HashMap,用来存储请求的响应缓存。这个缓存是线程安全的,因为被 Mutex 包裹了起来,这样就可以在多个线程中安全地访问和修改这个缓存。

接着定义了一个 RequestsResponseCache 结构体,用来表示缓存中的一个条目,其中包含了响应数据 response 和缓存的时间戳 datetime。

然后定义了一个 get_requests_response_cache 函数,用来从缓存中获取请求的响应。它首先尝试从缓存中获取指定 url 的响应数据,如果缓存中有对应的条目,并且距离上次缓存的时间超过了 3600 秒(1 小时),则重新发起请求并更新缓存,然后返回响应数据。如果缓存中没有对应的条目,或者缓存的时间未超过 3600 秒,则直接发起请求并更新缓存,然后返回响应数据。

这样就提供了一个简单的请求响应的缓存功能,能够在需要时缓存请求的响应数据,并在一定时间内有效,从而减少对远程服务的重复请求,提高程序性能。

相关推荐
johnsong2 小时前
AI前沿日报 · 2026-11-27:超人优化器、推理账单与 Rust 重写
rust·openai·anthropic·黎曼猜想·数学优化·ai前沿日报·gpt-6.2
جيون داد ناالام ميづ2 小时前
六、MyBatis 高级用法:动态 SQL 进阶 + 缓存优化 + TypeHandler
sql·缓存·mybatis
AlanAshley4 小时前
移动端省流方案:压缩+缓存
网络·缓存
陈工大模型5 小时前
MacOS 跨平台压缩包处理:从编码痛点到工程化落地的完整方案
windows·macos·缓存·电脑·策略模式·c盘清理
manduic17 小时前
APS256XXN 256Mb PSRAM 支撑 wisun 无线模块低功耗缓存
缓存
码完就睡18 小时前
Redis——初识 Redis
数据库·redis·缓存
钉先生贾1 天前
HarmonyOS 7.0 工程升级实战 40:构建缓存导致旧产物混入时,怎样隔离变量与复查
缓存·华为·harmonyos
Kapaseker1 天前
离开 Swift,转向 Rust
rust
钱栈up1 天前
GitHub 热榜实测|worktrunk 环境部署实录
rust·开源·github
船神丿男人2 天前
DevDocQA 的 Redis 答案缓存实战:版本切换、异步写回与故障排查
数据库·redis·缓存