我正在将 Next.js 用于我的业余项目。我有一个托管在 ElephantSQL 上的 PostgreSQL 数据库。在 Next.js 项目中,我使用 apollo-server-micro 包设置了 GraphQL API。
在设置 GraphQL API 的文件 (/api/graphql) 中,我导入一个数据库帮助程序模块。在其中,我设置了一个池连接并导出一个函数,该函数使用池中的客户端来执行查询并返回结果。这看起来像这样:
// import node-postgres module
import { Pool } from 'pg'
// set up pool connection using environment variables with a maximum of three active clients at a time
const pool = new Pool({ max: 3 })
// query function which uses next available client to execute a single query and return results on success
export async function queryPool(query) {
let payload
// checkout a client
try {
// try executing queries
const res = await pool.query(query)
payload = res.rows
} catch (e) {
console.error(e)
}
return payload
}
我遇到的问题是,Next.js API 似乎并不(总是)保持连接处于活动状态,而是打开一个新连接(对于每个连接的用户,甚至对于每个 API 查询) ,这会导致数据库很快耗尽连接。
我相信我想要实现的目标是可能的,例如在 AWS Lambda 中(通过设置context.callbackWaitsForEmptyEventLoop to false).
我很可能对无服务器功能如何工作没有正确的理解,这可能根本不可能,但也许有人可以建议我一个解决方案。
我找到了一个名为无服务器 postgres我想知道这是否能够解决这个问题,但我更喜欢使用 node-postgres 包,因为它有更好的文档。另一种选择可能是完全放弃集成的 API 功能并构建一个专用的后端服务器来维护数据库连接,但显然这将是最后的手段。
我还没有对此进行压力测试,但看起来mongodb next.js 示例 https://developer.mongodb.com/how-to/nextjs-with-mongodb/,通过附加数据库连接来解决这个问题global
在辅助函数中。他们的例子中重要的一点是here https://github.com/vercel/next.js/blob/canary/examples/with-mongodb/util/mongodb.js.
自从pg
连接比连接更抽象一些mongodb
,看来这种方法对我们来说只需要几行pg
爱好者:
// eg, lib/db.js
const { Pool } = require("pg");
if (!global.db) {
global.db = { pool: null };
}
export function connectToDatabase() {
if (!global.db.pool) {
console.log("No pool available, creating new pool.");
global.db.pool = new Pool();
}
return global.db;
}
然后在我们的 API 路由中,我们可以:
// eg, pages/api/now
export default async (req, res) => {
const { pool } = connectToDatabase();
try {
const time = (await pool.query("SELECT NOW()")).rows[0].now;
res.end(`time: ${time}`);
} catch (e) {
console.error(e);
res.status(500).end("Error");
}
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)