讀取副本
讀取副本讓您能夠跨資料庫副本分配工作負載,以應對高流量工作負載。讀取副本擴充功能@prisma/extension-read-replicas
,為 Prisma Client 新增了對唯讀資料庫副本的支援。
讀取副本擴充功能支援 Prisma ORM 版本 5.2.0 和更高版本。如果您遇到錯誤或有任何意見回饋,請在此處建立 GitHub issue here。
設定讀取副本擴充功能
安裝擴充功能
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
,都將針對上述設定的資料庫副本執行。所有寫入操作 — 例如 create
、update
— 和 $transaction
查詢,都將針對您的主要資料庫執行。
如果您遇到錯誤或有任何意見回饋,請在此處建立 GitHub issue here。
配置多個資料庫副本
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(...)