繁体   English   中英

API网关调用Lambda function间歇状态500错误

[英]Intermittent status 500 error on API gateway calling Lambda function

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

问题是我的 lambda function 有时会返回错误。 我的 lambda function 成功返回了大多数课程的信息,但返回了 2 个课程的连接错误。 并且此连接错误随机发生。 有时,根本不会发生任何错误。

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

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

 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]); } ); }); };

您的问题很可能与 RDS 连接池有关 - 较低的 RDS 实例在它们可以接受的并发连接数方面非常有限,如果它们命中它们就会出错。

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

您的代码是 lambda function 容器重用功能的受害者。

在您的处理程序中, 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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM