Skip to main content

连接管理

PrismaClient 使用以下两种方法连接和断开与数据源的连接:

¥PrismaClient connects and disconnects from your data source using the following two methods:

大多数情况下,你不需要显式调用这些方法。当你运行第一个查询时,PrismaClient 会自动连接,创建 连接池,并在 Node.js 进程结束时断开连接。

¥In most cases, you do not need to explicitly call these methods. PrismaClient automatically connects when you run your first query, creates a connection pool, and disconnects when the Node.js process ends.

请参阅 连接管理指南,了解有关管理不同部署范例(长时间运行的进程和无服务器功能)的连接的信息。

¥See the connection management guide for information about managing connections for different deployment paradigms (long-running processes and serverless functions).

$connect()

由于延迟连接行为,无需调用 $connect():当向 API 发送第一个请求时,PrismaClient 实例会延迟连接(在后台为你调用 $connect())。

¥It is not necessary to call $connect() thanks to the lazy connect behavior: The PrismaClient instance connects lazily when the first request is made to the API ($connect() is called for you under the hood).

显式调用 $connect()

¥Calling $connect() explicitly

如果你需要第一个请求立即响应并且无法等待惰性连接建立,则可以显式调用 prisma.$connect() 建立与数据源的连接:

¥If you need the first request to respond instantly and cannot wait for a lazy connection to be established, you can explicitly call prisma.$connect() to establish a connection to the data source:

const prisma = new PrismaClient()

// run inside `async` function
await prisma.$connect()

$disconnect()

当你调用 $disconnect() 时,Prisma 客户端:

¥When you call $disconnect() , Prisma Client:

  1. 运行 beforeExit

    ¥Runs the beforeExit hook

  2. 结束查询引擎子进程并关闭所有连接

    ¥Ends the Query Engine child process and closes all connections

在长时间运行的应用中,例如 GraphQL API,它不断地服务请求,每次请求后对 $disconnect() 没有意义 - 建立连接需要时间,并且作为每个请求的一部分这样做会减慢你的应用的速度。

¥In a long-running application such as a GraphQL API, which constantly serves requests, it does not make sense to $disconnect() after each request - it takes time to establish a connection, and doing so as part of each request will slow down your application.

提示

为了避免长时间运行的应用中出现过多连接,我们建议你 在你的应用中使用 PrismaClient 的单个实例

¥To avoid too many connections in a long-running application, we recommend that you use a single instance of PrismaClient across your application.

显式调用 $disconnect()

¥Calling $disconnect() explicitly

你应该显式调用 $disconnect() 的一种情况是脚本:

¥One scenario where you should call $disconnect() explicitly is where a script:

  1. 不经常运行(例如,每晚发送电子邮件的计划作业),这意味着它不会从与数据库的长时间运行连接中受益,并且

    ¥Runs infrequently (for example, a scheduled job to send emails each night), which means it does not benefit from a long-running connection to the database and

  2. 存在于长时间运行的应用的上下文中,例如后台服务。如果应用永远不会关闭,Prisma 客户端永远不会断开连接。

    ¥Exists in the context of a long-running application, such as a background service. If the application never shuts down, Prisma Client never disconnects.

以下脚本创建 PrismaClient 的新实例,执行任务,然后断开连接 - 关闭连接池:

¥The following script creates a new instance of PrismaClient, performs a task, and then disconnects - which closes the connection pool:

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()
const emailService = new EmailService()

async function main() {
const allUsers = await prisma.user.findMany()
const emails = allUsers.map((x) => x.email)

await emailService.send(emails, 'Hello!')
}

main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})

如果上述脚本在长时间运行的应用上下文中运行多次而不调用 $disconnect(),则会使用 PrismaClient 的每个新实例创建一个新连接池。

¥If the above script runs multiple times in the context of a long-running application without calling $disconnect(), a new connection pool is created with each new instance of PrismaClient.

退出钩子

¥Exit hooks

info

从 Prisma ORM 5.0.0 开始,beforeExit 钩子仅适用于 二进制查询引擎

¥From Prisma ORM 5.0.0, the beforeExit hook only applies to the binary Query Engine.

当 Prisma ORM 被外部触发(例如通过 SIGINT 信号)关闭时,beforeExit 钩子运行,并允许你在 Prisma 客户端断开连接之前运行代码 - 例如,作为服务正常关闭的一部分触发查询:

¥The beforeExit hook runs when Prisma ORM is triggered externally (e.g. via a SIGINT signal) to shut down, and allows you to run code before Prisma Client disconnects - for example, to issue queries as part of a graceful shutdown of a service:

const prisma = new PrismaClient()

prisma.$on('beforeExit', async () => {
console.log('beforeExit hook')
// PrismaClient still available
await prisma.message.create({
data: {
message: 'Shutting down server',
},
})
})