连接池
查询引擎管理数据库连接的连接池。当 Prisma 客户端打开与数据库的第一个连接时,会创建该池,这可以通过以下两种方式之一发生:
¥The query engine manages a connection pool of database connections. The pool is created when Prisma Client opens the first connection to the database, which can happen in one of two ways:
-
到 显式调用
$connect()
或 -
通过运行第一个查询,该查询在后台调用
$connect()
¥By running the first query, which calls
$connect()
under the hood
关系数据库连接器使用 Prisma ORM 自己的连接池,MongoDB 连接器使用 MongoDB 驱动连接池。
¥Relational database connectors use Prisma ORM's own connection pool, and the MongoDB connectors uses the MongoDB driver connection pool.
从 v6.7.0 开始,Prisma ORM 具有 queryCompiler
预览功能。
¥As of v6.7.0, Prisma ORM has the queryCompiler
Preview feature.
启用后,你的 Prisma 客户端将生成 无需基于 Rust 的查询引擎二进制文件:
¥When enabled, your Prisma Client will be generated without a Rust-based query engine binary:
generator client {
provider = "prisma-client-js"
previewFeatures = ["queryCompiler", "driverAdapters"]
}
请注意,驱动适配器 预览功能与 queryCompiler
功能同时启用。使用 queryCompiler
预览功能时,连接池由你正在使用的原生 JS 数据库驱动程序维护。
¥Note that the driver adapters Preview feature is required alongside queryCompiler
. When using the queryCompiler
Preview feature, the connection pool is maintained by the native JS database driver you're using.
关系数据库
¥Relational databases
关系数据库连接器使用 Prisma ORM 的连接池。连接池有连接限制和池超时,由连接 URL 参数控制。
¥The relational database connectors use Prisma ORM's connection pool. The connection pool has a connection limit and a pool timeout, which are controlled by connection URL parameters.
连接池的工作原理
¥How the connection pool works
以下步骤描述了查询引擎如何使用连接池:
¥The following steps describe how the query engine uses the connection pool:
-
¥The query engine instantiates a connection pool with a configurable pool size and pool timeout.
-
查询引擎创建一个连接并将其添加到连接池中。
¥The query engine creates one connection and adds it to the connection pool.
-
当查询到来时,查询引擎会从池中保留一个连接来处理查询。
¥When a query comes in, the query engine reserves a connection from the pool to process query.
-
如果连接池中没有可用的空闲连接,则查询引擎会打开额外的数据库连接并将其添加到连接池中,直到数据库连接数达到
connection_limit
定义的限制。¥If there are no idle connections available in the connection pool, the query engine opens additional database connections and adds them to the connection pool until the number of database connections reaches the limit defined by
connection_limit
. -
如果查询引擎无法从池中保留连接,查询将添加到内存中的 FIFO(先进先出)队列中。FIFO 意味着查询按照进入队列的顺序进行处理。
¥If the query engine cannot reserve a connection from the pool, queries are added to a FIFO (First In First Out) queue in memory. FIFO means that queries are processed in the order they enter the queue.
-
如果查询引擎无法在 时限 之前处理队列中的查询,则会针对该查询引发错误代码为
P2024
的异常,并继续处理队列中的下一个查询。¥If the query engine cannot process a query in the queue for before the time limit, it throws an exception with error code
P2024
for that query and moves on to the next one in the queue.
如果你持续遇到池超时错误,则需要 优化连接池 。
¥If you consistently experience pool timeout errors, you need to optimize the connection pool .
连接池大小
¥Connection pool size
默认连接池大小
¥Default connection pool size
默认连接数(池大小)通过以下公式计算:
¥The default number of connections (pool size) is calculated with the following formula:
num_physical_cpus * 2 + 1
num_physical_cpus
代表运行应用的计算机上的物理 CPU 数量。如果你的计算机有四个物理 CPU,则你的连接池将包含 9 个连接 (4 * 2 + 1 = 9
)。
¥num_physical_cpus
represents the number of physical CPUs on the machine your application is running on. If your machine has four physical CPUs, your connection pool will contain nine connections (4 * 2 + 1 = 9
).
尽管该公式代表了一个良好的起点,但 建议的连接限制 还取决于你的部署范例 - 特别是如果你使用无服务器。
¥Although the formula represents a good starting point, the recommended connection limit also depends on your deployment paradigm - particularly if you are using serverless.
设置连接池大小
¥Setting the connection pool size
你可以通过在数据库连接 URL 中显式设置 connection_limit
参数来指定连接数。例如,通过 Prisma 架构 中的以下 datasource
配置,连接池将恰好有 5 个连接:
¥You can specify the number of connections by explicitly setting the connection_limit
parameter in your database connection URL. For example, with the following datasource
configuration in your Prisma schema the connection pool will have exactly five connections:
datasource db {
provider = "postgresql"
url = "postgresql://johndoe:mypassword@localhost:5432/mydb?connection_limit=5"
}
查看连接池大小
¥Viewing the connection pool size
Prisma Client 使用的连接数可以使用 logging 和 metrics 查看。
¥The number of connections Prisma Client uses can be viewed using logging and metrics.
使用 info
记录级别,你可以记录 Prisma 客户端实例化时打开的连接池中的连接数。
¥Using the info
logging level, you can log the number of connections in a connection pool that are opened when Prisma Client is instantiated.
例如,考虑以下 Prisma 客户端实例和调用:
¥For example, consider the following Prisma Client instance and invocation:
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient({
log: ['info'],
})
async function main() {
await prisma.user.findMany()
}
main()
prisma:info Starting a postgresql pool with 21 connections.
当实例化 PrismaClient
类时,日志记录通知 stdout
启动了一个具有 21 个连接的连接池。
¥When the PrismaClient
class was instantiated, the logging notified stdout
that a connection pool with 21 connections was started.
请注意,log: ['info']
生成的输出可能会在任何版本中发生更改,恕不另行通知。如果你依赖应用或正在构建的工具中的输出,请注意这一点。
¥Note that the output generated by log: ['info']
can change in any release without notice. Be aware of this in case you are relying on the output in your application or a tool that you're building.
如果你需要更多地了解连接池的大小以及使用中和空闲连接的数量,你可以使用 metrics 功能(当前处于预览版)。
¥If you need even more insights into the size of your connection pool and the amount of in-use and idle connection, you can use the metrics feature (which is currently in Preview).
考虑以下示例:
¥Consider the following example:
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function main() {
await Promise.all([prisma.user.findMany(), prisma.post.findMany()])
const metrics = await prisma.$metrics.json()
console.dir(metrics, { depth: Infinity })
}
main()
{
"counters": [
// ...
{
"key": "prisma_pool_connections_open",
"labels": {},
"value": 2,
"description": "Number of currently open Pool Connections"
}
],
"gauges": [
// ...
{
"key": "prisma_pool_connections_busy",
"labels": {},
"value": 0,
"description": "Number of currently busy Pool Connections (executing a datasource query)"
},
{
"key": "prisma_pool_connections_idle",
"labels": {},
"value": 21,
"description": "Number of currently unused Pool Connections (waiting for the next datasource query to run)"
},
{
"key": "prisma_pool_connections_opened_total",
"labels": {},
"value": 2,
"description": "Total number of Pool Connections opened"
}
],
"histograms": [
/** ... **/
]
}
有关指标输出中可用内容的更多详细信息,请参阅 关于指标 部分。
¥For more details on what is available in the metrics output, see the About metrics section.
连接池超时
¥Connection pool timeout
默认池超时
¥Default pool timeout
默认连接池超时时间为 10 秒。如果查询引擎在这段时间内没有从数据库连接池获取连接,它将引发异常并继续执行队列中的下一个查询。
¥The default connection pool timeout is 10 seconds. If the Query Engine does not get a connection from the database connection pool within that time, it throws an exception and moves on to the next query in the queue.
设置连接池超时时间
¥Setting the connection pool timeout
你可以通过在数据库连接 URL 中显式设置 pool_timeout
参数来指定池超时。在以下示例中,池在 2
秒后超时:
¥You can specify the pool timeout by explicitly setting the pool_timeout
parameter in your database connection URL. In the following example, the pool times out after 2
seconds:
datasource db {
provider = "postgresql"
url = "postgresql://johndoe:mypassword@localhost:5432/mydb?connection_limit=5&pool_timeout=2"
}
禁用连接池超时
¥Disabling the connection pool timeout
你可以通过将 pool_timeout
参数设置为 0
来禁用连接池超时:
¥You disable the connection pool timeout by setting the pool_timeout
parameter to 0
:
datasource db {
provider = "postgresql"
url = "postgresql://johndoe:mypassword@localhost:5432/mydb?connection_limit=5&pool_timeout=0"
}
你可以选择 如果查询必须保留在队列中,请禁用连接池超时 - 例如,如果你正在并行导入大量记录,并且确信队列不会在作业完成之前耗尽所有可用 RAM。
¥You can choose to disable the connection pool timeout if queries must remain in the queue - for example, if you are importing a large number of records in parallel and are confident that the queue will not use up all available RAM before the job is complete.
MongoDB
MongoDB 连接器不使用 Prisma ORM 连接池。连接池由 MongoDB 驱动程序和 通过连接字符串参数配置 进行内部管理。
¥The MongoDB connector does not use the Prisma ORM connection pool. The connection pool is managed internally by the MongoDB driver and configured via connection string parameters.
外部连接池
¥External connection poolers
你不能将 connection_limit
增加到超出底层数据库可以支持的范围。这在无服务器环境中是一个特殊的挑战,其中每个功能都管理 PrismaClient
的一个实例 - 以及它自己的连接池。
¥You cannot increase the connection_limit
beyond what the underlying database can support. This is a particular challenge in serverless environments, where each function manages an instance of PrismaClient
- and its own connection pool.
考虑引入 外部连接池,例如 PgBouncer 以防止你的应用或函数耗尽数据库连接限制。
¥Consider introducing an external connection pooler like PgBouncer to prevent your application or functions from exhausting the database connection limit.
手动数据库连接处理
¥Manual database connection handling
使用 Prisma ORM 时,数据库连接在 engine 级别上处理。这意味着它们不会向开发者公开,并且无法手动访问它们。
¥When using Prisma ORM, the database connections are handled on an engine-level. This means they're not exposed to the developer and it's not possible to manually access them.