跳到主要內容

讀取副本

讀取副本使你能夠將工作負載分散到資料庫副本中,以處理高流量工作負載。讀取副本擴充套件@prisma/extension-read-replicas,為 Prisma Client 增加了只讀資料庫副本支援。

讀取副本擴充套件支援 Prisma ORM 5.2.0 及更高版本。如果你遇到 Bug 或有反饋,請在此建立 GitHub issue。

設定讀取副本擴充套件

安裝擴充套件

npm install @prisma/extension-read-replicas

透過擴充套件你的 Prisma Client 例項來初始化擴充套件,並在擴充套件的 url 選項中提供指向你的讀取副本的連線字串。

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 查詢都將針對你的主資料庫執行。

如果你遇到 Bug 或有反饋,請在此建立 GitHub issue。

配置多個數據庫副本

url 屬性也接受一個數組值,即所有你希望配置的資料庫副本的陣列

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

如果你配置了多個讀取副本,將隨機選擇一個數據庫副本來執行你的查詢。

針對主資料庫執行讀取操作

你可以使用 $primary() 方法明確地針對你的主資料庫執行讀取操作

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

針對資料庫副本執行操作

你可以使用 $replica() 方法明確地針對副本而非主資料庫執行查詢

const result = await prisma.$replica().user.findFirst(...)
© . This site is unofficial and not affiliated with Prisma Data, Inc.