关于 encore-cache
介绍 Encore 对 Redis 的类型化缓存封装,面向需要在 Encore 服务中缓存数据的开发者。通过集群和键空间定义数据类型、键模式及过期策略。
主要功能
- 01声明缓存集群和键空间
- 02提供多种键空间数据类型
- 03配置键模式和过期时间
- 04支持条件写入与原子计数操作
- 05处理缓存未命中和键冲突
适用场景
- 01按用户或资源路径缓存数据
- 02为计数器执行递增或递减
- 03为缓存值设置过期时间
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ encoredev/ skills --skill encore-cache安装后在 Claude Code 中输入/encore-cache确认已加载。
详细介绍
Encore 缓存(Redis)
说明
Encore 的缓存是 Redis 的类型化封装。只需声明一次 CacheCluster,然后为所需的每种数据结构创建 Keyspace 对象。
集群
import { CacheCluster } from "encore.dev/storage/cache";
const cluster = new CacheCluster("my-cache", {
evictionPolicy: "allkeys-lru",
});
从其他服务引用集群:const cluster = CacheCluster.named("my-cache");
驱逐策略:"allkeys-lru"(默认)、"noeviction"、"allkeys-lfu"、"allkeys-random"、"volatile-lru"、"volatile-lfu"、"volatile-ttl"、"volatile-random"。
Keyspace 类型
每个 keyspace 都有一个键结构(用于通过 keyPattern 构建 Redis 键)和一个值类型。
import {
StringKeyspace,
IntKeyspace,
FloatKeyspace,
StructKeyspace,
StringListKeyspace,
NumberListKeyspace,
StringSetKeyspace,
NumberSetKeyspace,
expireIn,
} from "encore.dev/storage/cache";
// Strings
const tokens = new StringKeyspace<{ tokenId: string }>(cluster, {
keyPattern: "token/:tokenId",
defaultExpiry: expireIn(3600 * 1000),
});
await tokens.set({ tokenId: "abc" }, "value");
const val = await tokens.get({ tokenId: "abc" }); // undefined on miss
// Integers (atomic counters)
const counters = new IntKeyspace<{ userId: string }>(cluster, {
keyPattern: "requests/:userId",
defaultExpiry: expireIn(10 * 1000),
});
const count = await counters.increment({ userId: "user123" }, 1);
// Structs (JSON)
interface UserProfile { name: string; email: string; }
const profiles = new StructKeyspace<{ userId: string }, UserProfile>(cluster, {
keyPattern: "profile/:userId",
defaultExpiry: expireIn(3600 * 1000),
});
await profiles.set({ userId: "123" }, { name: "Alice", email: "[email protected]" });
// Lists
const recent = new StringListKeyspace<{ userId: string }>(cluster, {
keyPattern: "recent/:userId",
});
await recent.pushRight({ userId: "user123" }, "item1", "item2");
// Sets
const tags = new StringSetKeyspace<{ articleId: string }>(cluster, {
keyPattern: "tags/:articleId",
});
await tags.add({ articleId: "post1" }, "typescript", "encore");
const has = await tags.contains({ articleId: "post1" }, "typescript");
多字段键模式
interface Key { userId: string; resourcePath: string; }
const requests = new IntKeyspace<Key>(cluster, {
keyPattern: "requests/:userId/:resourcePath",
defaultExpiry: expireIn(10 * 1000),
});
过期时间辅助方法
import {
expireIn, // milliseconds
expireInSeconds,
expireInMinutes,
expireInHours,
expireDailyAt, // a specific UTC time each day
neverExpire,
keepTTL, // keep existing TTL when updating
} from "encore.dev/storage/cache";
写入选项
await keyspace.set(key, value, { expiry: expireInMinutes(30) });
await keyspace.set(key, value, { expiry: keepTTL });
await keyspace.setIfNotExists(key, value); // throws CacheKeyExists if present
await keyspace.replace(key, value); // throws CacheMiss if absent
错误
import { CacheMiss, CacheKeyExists } from "encore.dev/storage/cache";
const value = await keyspace.get(key); // undefined on miss (does not throw)
指南
- 在包级别声明
CacheCluster和 keyspace。 - 选择最具体的 keyspace 类型——计数器使用
IntKeyspace,即可自动获得原子increment/decrement操作。 - 缓存未命中时,
get()会返回undefined;发生冲突时,replace()和setIfNotExists()会抛出错误。 - 本地开发使用的是内存中的 Redis,容量上限约为 100 个键——不要对其进行负载测试。
- 如需持久化存储,请改用
encore-database(Postgres)或encore-bucket(对象存储)。
评论
支持 Markdown