跳到主要内容

API 参考

Accelerate API 参考文档基于以下模式

model User {
id Int @id @default(autoincrement())
name String?
email String @unique
}

所有示例均基于 User 模型。

cacheStrategy

通过 Prisma Client 的 Accelerate 扩展,您可以将 cacheStrategy 参数用于模型查询,并使用 ttlswr 参数为 Accelerate 定义缓存策略。Accelerate 扩展要求您安装 Prisma Client 版本 4.10.0

选项

cacheStrategy 参数接受一个带有以下键的选项

选项示例类型必需描述
swr60Int以秒为单位的过时-同时-重新验证时间。
ttl60Int以秒为单位的生存时间。
tags["user"]String[]tag 用作控制应用程序中特定查询失效的变量。它是用于 使缓存失效 的可选字符串数组,每个标签仅包含字母数字字符和下划线,最大长度为 64 个字符。

示例

向查询添加缓存策略,定义 60 秒的过时-同时-重新验证 (SWR) 值、60 秒的生存时间 (TTL) 值以及 "emails_with_alice" 的缓存标签

await prisma.user.findMany({
where: {
email: {
contains: "[email protected]",
},
},
cacheStrategy: {
swr: 60,
ttl: 60,
tags: ["emails_with_alice"],
},
});

支持的 Prisma Client 操作

以下是支持 cacheStrategy 的所有读取查询操作的列表

信息

cacheStrategy 参数在任何写入操作(例如 create())上均不受支持。

withAccelerateInfo

任何支持 cacheStrategy 的查询都可以附加 withAccelerateInfo() 以包装响应数据并包含有关 Accelerate 响应的附加信息。

要检索响应的状态,请使用

const { data, info } = await prisma.user
.count({
cacheStrategy: { ttl: 60, swr: 600 },
where: { myField: 'value' },
})
.withAccelerateInfo()

console.dir(info)
信息

请注意响应对象的 info 属性。请求信息存储在此处。

返回类型

info 对象是 AccelerateInfo 类型,并遵循以下接口

interface AccelerateInfo {
cacheStatus: 'ttl' | 'swr' | 'miss' | 'none'
lastModified: Date
region: string
requestId: string
signature: string
}
属性类型描述
cacheStatus"ttl" | "swr" | "miss" | "none"响应的缓存状态。
  • ttl 表示在 ttl 持续时间内缓存命中,并且未执行数据库查询
  • swr 表示在 swr 持续时间内缓存命中,并且 Accelerate 正在后台刷新数据
  • miss 表示 ttlswr 都已过期,并且数据库查询已由请求执行
  • none 表示未指定缓存策略,并且数据库查询已由请求执行
lastModified日期响应上次刷新的日期。
regionString接收请求的数据中心区域。
requestIdString请求的唯一标识符。对故障排除很有用。
signatureStringPrisma 操作的唯一签名。

$accelerate.invalidate

您可以使用 $accelerate.invalidate API 使缓存失效。

注意

要按需使缓存的查询结果失效,需要付费计划。每个计划对每天允许的基于缓存标签的失效次数都有特定限制,但调用 $accelerate.invalidate API 本身没有限制。有关更多详细信息,请参阅我们的定价

示例

要使以下查询失效

await prisma.user.findMany({
where: {
email: {
contains: "[email protected]",
},
},
cacheStrategy: {
swr: 60,
ttl: 60,
tags: ["emails_with_alice"],
},
});

您需要在 $accelerate.invalidate API 中提供缓存标签

try {
await prisma.$accelerate.invalidate({
tags: ["emails_with_alice"],
});
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
// The .code property can be accessed in a type-safe manner
if (e.code === "P6003") {
console.log(
"The cache invalidation rate limit has been reached. Please try again later."
);
}
}
throw e;
}
注意

每次调用最多可以使 5 个标签失效。

错误

Prisma Accelerate 相关错误以 P6xxx 开头。

您可以在此处找到 Prisma Accelerate 的完整错误代码参考。