Skip to main content

Module l2_cache

Module l2_cache 

Source
Expand description

L2 二级缓存(Level-2 Cache)

对应文档 6.8 节改进项 21(L2 二级缓存)。

§核心概念

  • L2Cache:跨 Session 共享的二级缓存(与 Hibernate L2 Cache / MyBatis 二级缓存对应)
  • CacheKey:统一缓存键构造(table + pk 或 table + query_hash)
  • L2CacheStats:命中率统计(hits/misses/evictions/sets)
  • 表级失效invalidate_table(table) 一次失效某表的所有缓存项

与 L1 缓存(Session 级别)的区别:

  • L1:单次 Session/请求 内有效,事务结束自动清空
  • L2:跨 Session 共享,进程级缓存,需显式失效

§设计灵感

  • Hibernate L2 Cache(@Cache / @Cacheable
  • MyBatis 二级缓存(<cache> 标签)
  • Rails Rails.cache
  • Django cache framework

§使用示例

use sz_orm_core::l2_cache::{L2Cache, CacheKey};
use sz_orm_core::Value;

// 1. 创建 L2 缓存
let cache = L2Cache::new();

// 2. 缓存单行(pk 维度)
let key = CacheKey::by_pk("users", 1);
cache.put(&key, Value::String("Alice".to_string()), None);

// 3. 读取
let val = cache.get(&key);
assert!(val.is_some());

// 4. 表级失效(用户表更新后)
cache.invalidate_table("users");
assert!(cache.get(&key).is_none());

// 5. 命中率统计
let stats = cache.stats();
println!("hit rate: {:.2}%", stats.hit_rate() * 100.0);

Structs§

CacheKey
统一缓存键
L2Cache
L2 二级缓存 — 跨 Session 共享
L2CacheStats
L2 缓存命中率统计

Enums§

CacheKeyKind
缓存键类型