缓存

属于 kxed 全栈 Rust 后端框架生态:官网 | 在线文档 | 源码仓库 | 主包 crates.io

提供统一的 Cache 句柄,底层通过配置 cache.backend 在进程内有界 Moka 缓存与全集群共享 Redis 缓存之间无缝切换,内置 JSON 读穿、后台旧值刷新(SWR)、按标签批量失效、跨实例互斥锁、表单/Webhook 去重与排行榜有序集合。实战用法见 多语言、模板与 SSE 教程。

快速接入#

在 Cargo.toml 开启主包 kxed 的 cache 特性(多实例共享 Redis 缓存时改开 cache-redis 或 cluster-backends;独立组装可依赖 kxed-plugins = { version = "0.0.5-alpha", features = ["cache"] }):

TOML
[dependencies]
kxed = { version = "0.0.5-alpha", features = ["cache", "cache-redis"] }

在应用配置文件中选择缓存后端(单机默认 memory,集群配 redis):

TOML
[redis]
url = "redis://127.0.0.1:6379"

[cache]
backend = "redis"
time_to_live = "5m"

在应用中注册 CachePlugin::new(),并在业务 Procedure 中调用 ctx.cache()? 进行 JSON 读穿缓存:

Rust
use kxed::plugins::cache::CachePlugin;
use kxed::plugins::redis::RedisPlugin;
use kxed::prelude::*;
use std::time::Duration;

#[query(name = "users.greeting", get = "/api/greeting/{user}")]
pub async fn greeting(ctx: &AppCtx, user: String) -> Result<String, AppErr> {
    let key = format!("greeting:{user}");
    ctx.cache()?
        .get_or_compute_json(key, Duration::from_secs(60), || async {
            Ok::<_, AppErr>(format!("Hi, {user}"))
        })
        .await
}

#[kxed::main]
async fn main() -> kxed::Result<()> {
    App::new()
        .plugin(RedisPlugin::new())
        .plugin(CachePlugin::new())
        .run()
        .await
}

子 crate 独立接入最小示例:

Rust
use kxed_core::{AppCtx, AppErr};
use kxed_plugins::cache::{AppCtxCache, CachePlugin};
use std::time::Duration;

fn plugin() -> CachePlugin {
    CachePlugin::new()
}

async fn greeting(ctx: &AppCtx, user: &str) -> Result<String, AppErr> {
    let key = format!("greeting:{user}");
    ctx.cache()?
        .get_or_compute_json(key, Duration::from_secs(60), || async { Ok::<_, AppErr>(format!("Hi, {user}")) })
        .await
}

核心用法#

Cache 句柄#

通过 ctx.cache()? 获取句柄,所有错误变体均可直接用 ? 转为 AppErr:

场景分类方法行为说明
基础读写与失效get(key)、insert(key, val)、insert_with_ttl(key, val, ttl)、touch(key, ttl)、invalidate(key)、invalidate_all()读写字节切片或调整存活期;invalidate_all() 在 Redis 上通过递增代次键瞬间使旧键全集群失效
读穿与旧值后台刷新get_or_compute(key, ttl, f)、get_or_compute_json(key, ttl, f)、get_or_compute_stale(key, fresh, stale, f)未命中时执行闭包回填(缓存后端故障时自动降级直算返回,不阻断读请求);stale 在 fresh..stale 窗口内立即返回旧值并单飞后台异步重算
按标签批量失效tags(&["user:7", ..])返回 TaggedCache(含 get、insert、get_or_compute_json 与 invalidate()),调用 invalidate() 一键使该标签下全部缓存失效
原子计数与条件占位increment(key, delta, ttl)、insert_if_absent(key, val, ttl)、once(&hook, future)固定窗口限额计数、表单时间窗防重提交,以及按 VerifiedWebhook 自动去重执行一次(失败自动回滚占位)
互斥锁run_exclusive(key, ttl, work)、try_lock(key, ttl)、block(key, ttl, wait)同一 key 同一时刻仅运行一份任务(如 CLI 命令单实例执行);CacheLock 支持 release() 或跨内部通道 into_owner / restore_lock

常用模式代码示例(固定窗口配额、JSON 读穿、单实例互斥与防表单双击重复提交):

Rust
use kxed_core::{AppErr, StatusCode};
use kxed_plugins::cache::{Cache, CacheError};
use serde::{Deserialize, Serialize};
use std::time::Duration;

#[derive(Serialize, Deserialize)]
struct Plan {
    name: String,
    seats: u32,
}

async fn take_quota(cache: &Cache, user: &str, limit: i64) -> Result<bool, CacheError> {
    let used = cache.increment(format!("quota:{user}"), 1, Duration::from_secs(60)).await?;
    Ok(used <= limit)
}

async fn load_plan(cache: &Cache, account: &str) -> Result<Plan, AppErr> {
    cache
        .get_or_compute_json(format!("plan:{account}"), Duration::from_secs(300), || async {
            Ok(Plan { name: format!("{account}-team"), seats: 5 })
        })
        .await
}

async fn reconcile_once(cache: &Cache) -> Result<u64, AppErr> {
    let Some(done) = cache.run_exclusive("orders:reconcile", Duration::from_secs(3600), || async { Ok::<_, AppErr>(42) }).await? else {
        return Err(AppErr::new(StatusCode::SERVICE_UNAVAILABLE, "already running").with_code("orders_reconcile_busy"));
    };
    Ok(done)
}

async fn prevent_double_submit(cache: &Cache, user: &str, token: &str) -> Result<(), AppErr> {
    if !cache.insert_if_absent(format!("submit:{user}:{token}"), &b""[..], Duration::from_secs(10)).await? {
        return Err(AppErr::new(StatusCode::CONFLICT, "duplicate submission").with_code("orders_submission_conflict"));
    }
    Ok(())
}

互斥锁使用边界:缓存锁独立于普通缓存条目(不受容量淘汰与 invalidate_all 影响),但不携带 fencing token,适用于定时任务、运维命令单实例与后台防并发刷新;涉及资金扣款或库存扣减等强一致互斥场景,请使用 Resident 单实例串行或数据库事务行锁。

有序集合#

cache.sorted(name)(或指定集群同槽分组的 cache.sorted_in(group, name))返回排行榜句柄 SortedSet,在内存与 Redis 后端上提供完全一致的 i64 分数排序语义(高分在前,同分按成员名字典序升序):

  • 支持方法:add、incr、top、rank、score、remove、expire 与 clear(排行榜键不带代次号,不受 Cache::invalidate_all 清理影响,清空榜单请显式调用 SortedSet::clear)。

Config#

keydefaultcontract
cache.backendmemorymemory(进程内 Moka)或 redis(需开启 cache-redis 并注册配置了 redis.url 的 RedisPlugin)
cache.max_capacity_bytes67108864内存后端总字节权重上限(默认 64 MiB),范围 1..=1073741824
cache.max_entries65536内存后端最大条目数上限,范围 1..=1048576
cache.time_to_live5m默认绝对过期时间,null 或 1s..=31536000000s(Redis 后端下与 time_to_idle 至少配一项)
cache.time_to_idlenull空闲未访问过期时间,null 或 1s..=31536000000s(命中续期但不越过绝对 time_to_live)
cache.redis.prefixdefaultRedis 键命名空间前缀(1..=64 字节不含 : 的可打印 ASCII,集群内各节点必须一致)
cache.redis.max_value_bytes1048576Redis 后端单条缓存值大小上限(默认 1 MiB),范围 1..=16777216
cache.redis.generation_refresh_interval1s本机缓存 invalidate_all 全局代次号的刷新间隔,范围 100ms..=60s

运行期边界与后端实现细节#

错误分类(CacheError)#

变体触发条件HTTP 状态码与重试语义
Unavailable请求发出前连接中断/队列满,或进程内锁表(上限 65,536 把)已满503,NotExecuted(未执行,可安全重发)
LockTimeoutblock(key, ttl, wait) 等待期满仍未拿到互斥锁503 cache_lock_timeout,NotExecuted
Indeterminateincrement 或 insert_if_absent 发出后超时断连,服务端可能已落盘504,Indeterminate(非幂等累加勿盲目重发)
KeyTooLarge / ValueTooLarge键超过 MAX_KEY_BYTES(1024 字节)或值超过后端容量上限400 / 413,Settled
NotACounter对普通缓存值键调用 increment 或 i64 溢出409,Settled

进程内后端与多实例检查#

  • 进程内维护与锁隔离:memory 后端读取零拷贝返回 Arc<[u8]>,后台受管任务每 300ms 推进 Moka 维护队列;互斥锁独立存放在有序到期表中,不与普通缓存争抢容量。直接基于 kxed-core 自建宿主(不经 kxed 主包)时需在启动前注入 ProcessTopology。
  • 集群防误配检查:开启 fabric.discovery.mode 或配置 fabric.seeds 启动多实例集群时,若仍为 cache.backend = "memory" 且未在 fabric.allow_process_local 显式列出 cache,启动直接报错(运行期动态组网则将 /metrics 中的 kxed_cache_degraded 置 1 并写 warn,对比见 扩容指南)。

Redis 后端#

  • 兼容单机、Sentinel 与 Cluster:普通读写、计数、互斥锁、标签代次与 invalidate_all(递增 kxed:cache:<prefix>:gen)均为单键操作,无需跨槽位,只有 sorted_in(group, name) 使用 {group} hash tag。读取通过 GETRANGE 限制最大拉取字节数,版本格式不匹配的旧值自动按未命中处理并计入 kxed_cache_value_format_unknown_total。
  • 生产驱逐策略要求:承载互斥锁、Webhook 去重标记或排行榜有序集合的 Redis 实例,必须将 maxmemory-policy 设为 noeviction,防止内存满时提前驱逐尚未到期的锁或榜单成员;主从异步复制故障切换期间刚写入的缓存或锁存在回退窗口。