是否有关于如何通过 Lambda 连接到 AWS Aurora Serverless PostgreSQL 的 Node.js 示例

Aar*_*tin 5 node.js aws-lambda aws-aurora-serverless

我已经设置了一个 AWS Aurora Serverless PostgreSQL 数据库。我还有 API Gateway 运行 Lambda 函数的端点。现在,Lambda 函数正在连接到 DynamoDB,但 RDS 将更适合我的用例。

我已经在互联网上搜索了几个小时,但似乎找不到关于如何使用 Node.js 通过 Lambda 访问我的 Aurora Serverless DB 的示例。我不确定我的函数中需要哪些导入,而且我也很难在 API 中找到正确的方法。

只是一个让我入门的基本 Node.js 示例会非常有帮助。

提前致谢。

Aar*_*tin 1

我在 AWS 开发者论坛上得到了回复,这正是我开始使用所需要的。

显然,要使用 PostgreSQL 连接器,您必须在本地构建函数并导入,而不是使用在线 Lambda 控制台。

以下是 MrK 提供的示例代码: https ://forums.aws.amazon.com/message.jspa?messageID=919394

//this imports the postgres connector into the file so it can be used
const { Client } = require('pg');

//instantiates a client to connect to the database, connection settings are passed in
const client = new Client({
    user: '<your db username>',
    host: '<your endpoint>',
    database: '<your database name>',
    password: '<your database password>',
    port: 5432
});

//the lambda funtion code
exports.handler = async (event, context, callback) => {

    try {

        await client.connect();
        callback(null, "Connected Successfully");
        //your code here

    } catch (err) {

        callback(null, "Failed to Connect Successfully");
        throw err;
        //error message
    }

    client.end();

};
Run Code Online (Sandbox Code Playgroud)

  • 这不是连接到 Aurora Serverless 的方式。这适用于连接到普通 RDS 实例。然而,这不是一个好的解决方案,因为它会在每次调用中创建一个连接,这很慢,并且如果您有很多用户,很快就会使数据库耗尽可用连接。要连接到 Aurora Serverless,请使用 AWS SDK 中 RDSDataService 的数据 API,如 Mark B 在对问题本身的评论中提到的那样。 (10认同)