微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

您可以在Next.js API中保持PostgreSQL连接的活动状态吗?

如何解决您可以在Next.js API中保持PostgreSQL连接的活动状态吗?

我正在将Next.js用于我的副项目。我在Elephantsql上托管了一个Postrgesql数据库。在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 设置为 false )。

我很可能对无服务器功能的工作方式没有足够的了解,这也许根本不可能,但是也许有人可以向我提出解决方案。

我找到了一个名为 serverless-postgres 的软件包,我想知道这是否能够解决该问题,但我宁愿使用node-postgres软件包,因为它具有更好的文档。另一个选择可能是完全放弃集成的API功能,而建立一个专用的后端服务器,该服务器维护数据库连接,但是显然这将是最后的选择。

解决方法

我还没有对此进行压力测试,但似乎 mongodb next.js example 通过在辅助函数中将数据库连接附加到 global 解决了这个问题。他们示例中的重要部分是 here

由于 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");
  }
};

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。