【问题标题】:Can you keep a PostgreSQL connection alive from within a Next.js API?您可以在 Next.js API 中保持 PostgreSQL 连接处于活动状态吗?
【发布时间】:2021-01-13 12:39:24
【问题描述】:

我将 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 功能并构建一个专用的后端服务器,该服务器维护数据库连接,但显然这是最后的手段。

【问题讨论】:

  • 好问题,有什么好的解决方案吗? Br
  • @user1665355 遗憾的是没有。有一个 mysql-serverless 模块应该可以解决 MySQL 数据库连接的这个问题,但不幸的是,没有可用于 Postgres 的类似模块。我真的希望将来有人会创建一个,但在那之前我们将不得不使用第二个专用的数据库连接服务器。

标签: node.js postgresql next.js serverless node-postgres


【解决方案1】:

我还没有对此进行压力测试,但似乎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");
  }
};

【讨论】:

    猜你喜欢
    • 2012-01-03
    • 2021-09-13
    • 2013-08-27
    • 2019-09-01
    • 1970-01-01
    • 2012-07-08
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多