【问题标题】:Intermittent status 500 error on API gateway calling Lambda functionAPI 网关调用 Lambda 函数时出现间歇性状态 500 错误
【发布时间】:2021-09-29 14:09:25
【问题描述】:

我是 AWS 的新手,我正在尝试创建一个简单的 Web 服务来调用和显示有关我学校课程的信息。我通过 RDS 设置我的数据库,并编写 Lambda 函数来处理对数据库的请求,并使用 API 网关调用每个 API。

问题是我的 lambda 函数有时会返回错误。我的 lambda 函数成功返回有关大多数课程的信息,但返回 2 门课程的连接错误。而且这个连接错误是随机发生的。有时,根本不会发生错误。

我使用 Cloudwatch 查看我的控制台,错误消息是“无法读取未定义的属性'查询'。检查您的 Lambda 函数代码并重试。”。我认为这个错误是由于连接到我的数据库失败造成的。但是,我的 lambda 函数在大多数情况下都能正常工作。

我试图搜索类似的案例,但找不到。这是我的 lambda 函数。

const mysql = require("mysql");
const config = require("./config.json");

const pool = mysql.createPool({
  host: config.dbhost,
  user: config.dbuser,
  password: config.dbpassword,
  database: config.dbname,                // this is the max number of connections before your pool starts waiting for a release
  multipleStatements : true  
});
exports.handler = (event, context, callback) => {
  //prevent timeout from waiting event loop
  context.callbackWaitsForEmptyEventLoop = false;
  pool.getConnection(function (err, connection) {
    // Use the connection
    connection.query(
      "SELECT * from course where id = " + event.pathParameters.id,
      function (error, results, fields) {
        // And done with the connection.
        connection.release();
        // Handle error after the release.
        if (error) callback(error);
        else callback(null, results[0]);
      }
    );
  });
};

【问题讨论】:

  • 尽量不要使用连接池。然后,在您的处理程序内部连接到您的数据库,完成您的工作,然后断开连接。

标签: amazon-web-services aws-lambda aws-api-gateway http-status-code-500


【解决方案1】:

您的问题很可能与 RDS 连接池有关 - RDS 实例越低,它们可以接受的同时连接数非常有限,如果它们遇到错误,它们就会出错。

我建议您设置一些异常处理和日志记录语句(即使只是打印到标准输出通常会在 CloudWatch 中结束)以查看错误发生时的错误,而不是依赖 api 网关 - 任何lambda 中抛出的未捕获异常会自动在 api 网关中导致 500 错误,除非您故意更改其行为,这使得跟踪正在发生的事情变得更加困难。

【讨论】:

  • 我扩大了我的 RDS,错误似乎得到了解决。谢谢
【解决方案2】:

您的代码是 lambda 函数容器重用能力的牺牲品。

在您的处理程序内部connection.release() 将在每次代码成功执行时释放连接。

必读:

Lambda functions execute in a container (sandbox), which provides isolation from
other functions and an allocation of resources such as memory, disk space, and CPU.
Container reuse is important to understand for more advanced uses of Lambda.
When a function is instantiated for the first time, a new container is initialized and the
code for the function is loaded (we say that the function is cold when this is done for
the first time). If a function is rerun (within a certain period), Lambda may reuse the
same container and skip the initialization process (we say that the function is now
warm), thus making it available to execute code quicker.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-14
    • 2020-10-24
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 2018-06-15
    相关资源
    最近更新 更多