Skip to main content

读取副本

只读副本使你能够跨数据库副本分配工作负载,以应对高流量工作负载。读取副本扩展@prisma/extension-read-replicas 向 Prisma 客户端添加了对只读数据库副本的支持。

¥Read replicas enable you to distribute workloads across database replicas for high-traffic workloads. The read replicas extension, @prisma/extension-read-replicas, adds support for read-only database replicas to Prisma Client.

只读副本扩展支持 Prisma ORM 版本 5.2.0 及更高版本。如果你遇到错误或有反馈,请创建 GitHub 问题 此处

¥The read replicas extension supports Prisma ORM versions 5.2.0 and higher. If you run into a bug or have feedback, create a GitHub issue here.

设置只读副本扩展

¥Setup the read replicas extension

安装扩展:

¥Install the extension:

npm install @prisma/extension-read-replicas

通过扩展 Prisma 客户端实例来初始化扩展,并为扩展提供一个指向扩展的 url 选项中的只读副本的连接字符串。

¥Initialize the extension by extending your Prisma Client instance and provide the extension a connection string that points to your read replica in the url option of the extension.

import { PrismaClient } from '@prisma/client'
import { readReplicas } from '@prisma/extension-read-replicas'

const prisma = new PrismaClient().$extends(
readReplicas({
url: process.env.DATABASE_URL_REPLICA,
})
)

// Query is run against the database replica
await prisma.post.findMany()

// Query is run against the primary database
await prisma.post.create({
data: {/** */},
})

所有读取操作,例如 findMany,将针对具有上述设置的数据库副本执行。所有写操作 - 例如 createupdate$transaction 查询将针对你的主数据库执行。

¥All read operations, e.g. findMany, will be executed against the database replica with the above setup. All write operations — e.g. create, update — and $transaction queries, will be executed against your primary database.

如果你遇到错误或有反馈,请创建 GitHub 问题 此处

¥If you run into a bug or have feedback, create a GitHub issue here.

配置多个数据库副本

¥Configure multiple database replicas

url 属性还接受一个值数组,即你想要配置的所有数据库副本的数组:

¥The url property also accepts an array of values, i.e. an array of all your database replicas you would like to configure:

const prisma = new PrismaClient().$extends(
readReplicas({
url: [
process.env.DATABASE_URL_REPLICA_1,
process.env.DATABASE_URL_REPLICA_2,
],
})
)

如果你配置了多个只读副本,系统将随机选择一个数据库副本来执行你的查询。

¥If you have more than one read replica configured, a database replica will be randomly selected to execute your query.

对主数据库执行读取操作

¥Executing read operations against your primary database

你可以使用 $primary() 方法对主数据库显式执行读取操作:

¥You can use the $primary() method to explicitly execute a read operation against your primary database:

const posts = await prisma.$primary().post.findMany()

对数据库副本执行操作

¥Executing operations against a database replica

你可以使用 $replica() 方法对副本而不是主数据库显式执行查询:

¥You can use the $replica() method to explicitly execute your query against a replica instead of your primary database:

const result = await prisma.$replica().user.findFirst(...)