serverpod-caching
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseServerpod Caching
Serverpod 缓存
In-memory and optional Redis caches via . Cached objects must be serializable models or primitives supported by Serverpod.
session.caches通过实现内存缓存及可选的Redis缓存。被缓存的对象必须是Serverpod支持的可序列化模型或基本数据类型。
session.cachesCache types
缓存类型
- — in-memory, current server instance
session.caches.local - — in-memory, for frequently accessed entries
session.caches.localPrio - — Redis-backed, shared across instances (requires Redis config; do not use without Redis enabled)
session.caches.global - — local query cache used by generated database helpers
session.caches.query
- — 内存缓存,仅作用于当前服务器实例
session.caches.local - — 内存缓存,用于频繁访问的缓存条目
session.caches.localPrio - — 基于Redis的缓存,跨服务器实例共享(需配置Redis;未启用Redis时请勿使用)
session.caches.global - — 由生成的数据库助手使用的本地查询缓存
session.caches.query
Basic usage
基本用法
dart
await session.caches.local.put('UserData-$userId', userData,
lifetime: Duration(minutes: 5));
var userData = await session.caches.local.get<UserData>('UserData-$userId');dart
await session.caches.local.put('UserData-$userId', userData,
lifetime: Duration(minutes: 5));
var userData = await session.caches.local.get<UserData>('UserData-$userId');CacheMissHandler
CacheMissHandler
Load on miss and store automatically:
dart
var userData = await session.caches.local.get(
'UserData-$userId',
CacheMissHandler(
() async => UserData.db.findById(session, userId),
lifetime: Duration(minutes: 5),
),
);Returns if the handler returns (nothing stored).
nullnull缓存未命中时自动加载并存储:
dart
var userData = await session.caches.local.get(
'UserData-$userId',
CacheMissHandler(
() async => UserData.db.findById(session, userId),
lifetime: Duration(minutes: 5),
),
);如果处理器返回,则返回(无内容被存储)。
nullnullCollections and primitives
集合与基本数据类型
dart
await session.caches.local.put('userCount', 17, lifetime: Duration(minutes: 5));
var count = await session.caches.local.get<int>('userCount');If relevant set a lifetime to avoid unbounded growth. Use stable, unique keys (e.g. ).
'EntityName-$id'dart
await session.caches.local.put('userCount', 17, lifetime: Duration(minutes: 5));
var count = await session.caches.local.get<int>('userCount');相关场景下请设置生命周期以避免缓存无限增长。使用稳定且唯一的缓存键(例如)。
'EntityName-$id'Pitfalls
注意事项
- asserts Redis is enabled; it is not a safe no-op fallback.
session.caches.global - Cache groups (+
put(..., group: 'name')) only work on the local caches.invalidateGroup('name')throwsinvalidateGroupon the Redis-backed global cache, so invalidate those entries by key withUnimplementedError.invalidateKey
- 会校验Redis是否启用;它并非安全的空操作降级方案。
session.caches.global - 缓存分组(+
put(..., group: 'name'))仅在本地缓存中生效。在基于Redis的全局缓存中调用invalidateGroup('name')会抛出invalidateGroup,因此需使用UnimplementedError按缓存键来失效这些条目。invalidateKey