Skip to main content

Prisma Accelerate 入门

先决条件

¥Prerequisites

要开始使用 Accelerate,你需要以下条件:

¥To get started with Accelerate, you will need the following:

  • 一个

    ¥A

  • 一个使用 Prisma 客户端 4.16.1 或更高版本的项目。如果你的项目使用交互式事务,则需要使用 5.1.1 或更高版本。(我们始终建议使用最新版本的 Prisma。)

    ¥A project that uses Prisma Client 4.16.1 or higher. If your project is using interactive transactions, you need to use 5.1.1 or higher. (We always recommend using the latest version of Prisma.)

  • 托管的 PostgreSQL、MySQL/MariaDB、PlanetScale、CockroachDB 或 MongoDB 数据库

    ¥A hosted PostgreSQL, MySQL/MariaDB, PlanetScale, CockroachDB, or MongoDB database

1. 启用 Accelerate

¥ Enable Accelerate

导航到你的 Prisma 数据平台项目,选择一个环境,然后通过提供数据库连接字符串并选择离你的数据库最近的区域来启用 Accelerate。

¥Navigate to your Prisma Data Platform project, choose an environment, and enable Accelerate by providing your database connection string and selecting the region nearest your database.

注意

如果你需要 IP 许可列表或包含受信任 IP 地址的防火墙配置,请启用静态 IP 以增强安全性。了解更多关于 如何在平台控制台中为 Accelerate 启用静态 IP 的信息。

¥If you require IP allowlisting or firewall configurations with trusted IP addresses, enable Static IP for enhanced security. Learn more on how to enable static IP for Accelerate in the Platform Console.

2. 将 Accelerate 添加到你的应用

¥ Add Accelerate to your application

2.1.更新你的数据库连接字符串

¥2.1. Update your database connection string

启用后,系统将提示你生成 API 密钥,你将在新的 Accelerate 连接字符串中使用该密钥来验证请求。

¥Once enabled, you'll be prompted to generate an API key that you'll use in your new Accelerate connection string to authenticate requests.

将直接数据库 URL 替换为新的 Accelerate 连接字符串。

¥Replace your direct database url with your new Accelerate connection string.

.env
# New Accelerate connection string with generated API_KEY
DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=__API_KEY__"

# Previous (direct) database connection string
# DATABASE_URL="postgresql://user:password@host:port/db_name?schema=public"

更新的连接字符串将用作 Prisma 模式文件中的数据源 url

¥Your updated connection string will be used as the datasource url in your Prisma schema file;

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

Prisma Migrate 和 Introspection 不支持 prisma:// 连接字符串。为了继续使用这些功能,请向 .env 文件添加一个名为 DIRECT_DATABASE_URL 的新变量,其值是直接数据库连接字符串:

¥Prisma Migrate and Introspection do not work with a prisma:// connection string. In order to continue using these features add a new variable to the .env file named DIRECT_DATABASE_URL whose value is the direct database connection string:

.env
DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=__API_KEY__"
DIRECT_DATABASE_URL="postgresql://user:password@host:port/db_name?schema=public"

然后在 Prisma 模式的 datasource 块中添加一个名为 directUrl 的字段,内容如下:

¥Then in your Prisma schema's datasource block add a field named directUrl with the following:

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_DATABASE_URL")
}

当提供此配置时,迁移和自省将使用 directUrl 连接字符串,而不是 url 中定义的连接字符串。

¥Migrations and introspections will use the directUrl connection string rather than the one defined in url when this configuration is provided.

directUrl 可用于执行迁移和自检。但是,你不需要 directUrl 即可在应用中使用 Accelerate。

¥directUrl is useful for you to carry out migrations and introspections. However, you don't need directUrl to use Accelerate in your application.

注意

如果你将 Prisma 与 PostgreSQL 结合使用,则无需 directUrl,因为 Prisma Migrate 和 Introspection 可以使用 prisma+postgres:// 连接字符串。

¥If you are using Prisma with PostgreSQL, there is no need for directUrl, as Prisma Migrate and Introspection work with the prisma+postgres:// connection string.

2.2.安装 Accelerate Prisma 客户端扩展

¥2.2. Install the Accelerate Prisma Client extension

信息

💡 Accelerate 需要 Prisma 客户端 版本 4.16.1 或更高版本以及 @prisma/extension-accelerate 版本 1.0.0 或更高版本。

¥💡 Accelerate requires Prisma Client version 4.16.1 or higher and @prisma/extension-accelerate version 1.0.0 or higher.

💡 Accelerate 扩展 @prisma/extension-accelerate 版本 2.0.0 及更高版本需要 Node.js 版本 18 或更高版本。

¥💡 Accelerate extension @prisma/extension-accelerate version 2.0.0 and above requires Node.js version 18 or higher.

安装最新版本的 Prisma 客户端和 Accelerate Prisma 客户端扩展

¥Install the latest version of Prisma Client and Accelerate Prisma Client extension

npm install @prisma/client@latest @prisma/extension-accelerate

2.3.为 Accelerate 生成 Prisma 客户端

¥2.3. Generate Prisma Client for Accelerate

如果你使用的是 Prisma 5.2.0 或更高版本,Prisma 客户端将根据数据库连接字符串中的协议自动确定如何连接数据库。如果 DATABASE_URL 中的连接字符串以 prisma:// 开头,Prisma 客户端将尝试使用 Prisma Accelerate 连接到你的数据库。

¥If you're using Prisma version 5.2.0 or greater, Prisma Client will automatically determine how it should connect to the database depending on the protocol in the database connection string. If the connection string in the DATABASE_URL starts with prisma://, Prisma Client will try to connect to your database using Prisma Accelerate.

在长期运行的应用服务器(例如部署在 AWS EC2 上的服务器)中使用 Prisma Accelerate 时,你可以通过执行以下命令来生成 Prisma 客户端:

¥When using Prisma Accelerate in long-running application servers, such as a server deployed on AWS EC2, you can generate the Prisma Client by executing the following command:

npx prisma generate

在无服务器或边缘应用中使用 Prisma Accelerate 时,我们建议你运行以下命令来生成 Prisma 客户端:

¥When using Prisma Accelerate in a Serverless or an Edge application, we recommend you to run the following command to generate Prisma Client:

npx prisma generate --no-engine

--no-engine 标志可防止查询引擎文件包含在生成的 Prisma 客户端中,从而确保你的应用包大小保持较小。

¥The --no-engine flag prevents a Query Engine file from being included in the generated Prisma Client, this ensures the bundle size of your application remains small.

警告

如果你的 Prisma 版本低于 5.2.0,请使用 --accelerate 选项生成 Prisma 客户端:

¥If your Prisma version is below 5.2.0, generate Prisma Client with the --accelerate option:

npx prisma generate --accelerate

如果你的 Prisma 版本低于 5.0.0,请使用 --data-proxy 选项生成 Prisma 客户端:

¥If your Prisma version is below 5.0.0, generate Prisma Client with the --data-proxy option:

npx prisma generate --data-proxy

2.4.使用 Accelerate 扩展扩展你的 Prisma 客户端实例

¥2.4. Extend your Prisma Client instance with the Accelerate extension

添加以下内容以使用 Accelerate 扩展来扩展你现有的 Prisma 客户端实例:

¥Add the following to extend your existing Prisma Client instance with the Accelerate extension:

import { PrismaClient } from '@prisma/client'
import { withAccelerate } from '@prisma/extension-accelerate'

const prisma = new PrismaClient().$extends(withAccelerate())

如果你要部署到边缘运行时(例如 Cloudflare Workers、Vercel Edge Functions、Deno Deploy 或 Supabase Edge Functions),请使用我们的边缘客户端:

¥If you are going to deploy to an edge runtime (like Cloudflare Workers, Vercel Edge Functions, Deno Deploy, or Supabase Edge Functions), use our edge client instead:

import { PrismaClient } from '@prisma/client/edge'
import { withAccelerate } from '@prisma/extension-accelerate'

const prisma = new PrismaClient().$extends(withAccelerate())

如果 VS Code 无法识别 $extends 方法,请参考 本节 了解如何解决问题。

¥If VS Code does not recognize the $extends method, refer to this section on how to resolve the issue.

将 Accelerate 扩展与其他扩展或中间件一起使用

¥Using the Accelerate extension with other extensions or middleware

扩展程序逐个应用 开始,请确保按正确的顺序应用它们。扩展无法共享行为,最后应用的扩展具有优先权。

¥Since extensions are applied one after another, make sure you apply them in the correct order. Extensions cannot share behavior and the last extension applied takes precedence.

如果你在应用中使用 Prisma 优化,请确保在 Accelerate 扩展之前应用它。例如:

¥If you are using Prisma Optimize in your application, make sure you apply it before the Accelerate extension. For example:

const prisma = new PrismaClient().$extends(withOptimize()).$extends(withAccelerate())

如果你在应用中使用 Prisma 中间件,请确保在任何 Prisma 客户端扩展(例如 Accelerate)之前添加它们。例如:

¥If you are using Prisma Middleware in your application, make sure they are added before any Prisma Client extensions (like Accelerate). For example:

const prisma = new PrismaClient().$use(middleware).$extends(withAccelerate())

2.5.在数据库查询中使用 Accelerate

¥2.5. Use Accelerate in your database queries

withAccelerate 扩展主要完成两项任务:

¥The withAccelerate extension primarily does two things:

  • 允许你访问每个适用模型方法中的 cacheStrategy 字段,从而允许你为每个查询定义缓存策略。

    ¥Gives you access to the cacheStrategy field within each applicable model method that allows you to define a cache strategy per-query.

  • 通过连接池路由所有查询。

    ¥Routes all of your queries through a connection pooler.

没有缓存策略,仅使用连接池

¥No cache strategy to only use connection pool

如果你只想利用 Accelerate 的连接池功能而不应用缓存策略,你可以按照不使用 Accelerate 的方式运行查询。

¥If you simply want to take advantage of Accelerate's connection pooling feature without applying a cache strategy, you may run your query the same way you would have without Accelerate.

通过启用 Accelerate 并提供 Accelerate 连接字符串,你的查询现在默认使用连接池。

¥By enabling Accelerate and supplying the Accelerate connection string, your queries now use the connection pooler by default.

定义缓存策略

¥Define a cache strategy

使用新的 cacheStrategy 属性更新查询,该属性允许你为该特定查询定义缓存策略:

¥Update a query with the new cacheStrategy property which allows you to define a cache strategy for that specific query:

const user = await prisma.user.findMany({
where: {
email: {
contains: 'alice@prisma.io',
},
},
cacheStrategy: { swr: 60, ttl: 60 },
})

在上面的示例中,swr: 60ttl: 60 表示 Accelerate 将提供缓存数据 60 秒,然后再提供 60 秒,同时 Accelerate 在后台获取新数据。

¥In the example above, swr: 60 and ttl: 60 means Accelerate will serve cached data for 60 seconds and then another 60 seconds while Accelerate fetches fresh data in the background.

现在你应该看到缓存查询的性能提升。

¥You should now see improved performance for your cached queries.

info

有关哪种策略最适合你的应用的信息,请参阅 选择缓存策略

¥For information about which strategy best serves your application, see Select a cache strategy.

信息

从 Prisma 5.2.0 版本开始,你可以将 Prisma Studio 与 Accelerate 连接字符串一起使用。

¥As of Prisma version 5.2.0 you can use Prisma Studio with the Accelerate connection string.

使缓存失效并保持缓存查询结果为最新

¥Invalidate the cache and keep your cached query results up-to-date

如果你的应用需要实时或近实时数据,缓存失效功能可确保用户看到最新的数据,即使在使用较大的 ttl(Time-To-Live)或 swr(Stale-While-Revalidate)缓存策略 时也是如此。通过使缓存失效,你可以绕过延长的缓存周期,以便在需要时显示实时数据。

¥If your application requires real-time or near-real-time data, cache invalidation ensures that users see the most current data, even when using a large ttl (Time-To-Live) or swr (Stale-While-Revalidate) cache strategy. By invalidating your cache, you can bypass extended caching periods to show live data whenever it's needed.

例如,如果仪表板显示客户信息,并且客户的联系方式发生变化,缓存失效功能允许你立即刷新该数据,确保支持人员始终看到最新信息,而无需等待缓存过期。

¥For example, if a dashboard displays customer information and a customer’s contact details change, cache invalidation allows you to refresh only that data instantly, ensuring support staff always see the latest information without waiting for the cache to expire.

要使缓存的查询结果无效,你可以添加标签,然后使用 $accelerate.invalidate API。

¥To invalidate a cached query result, you can add tags and then use the $accelerate.invalidate API.

注意

我们的付费计划提供按需缓存失效功能。更多详细信息,请参阅我们的 pricing

¥On-demand cache invalidation is available with our paid plans. For more details, please see our pricing.

要使以下查询无效:

¥To invalidate the query below:

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

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

¥You need to provide the cache tag in the $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(
"You've reached the cache invalidation rate limit. Please try again shortly."
);
}
}
throw e;
}