API网关调用Lambda函数时间歇性状态500错误



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

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

我用Cloudwatch查看我的控制台,错误信息是&;Cannot read property 'query' of undefined。检查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]);
}
);
});
};

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

我建议你设置一些异常处理和日志语句(甚至只是打印到性病通常会在监测)的错误是当它发生,而不是依靠api网关-λ自动结果中抛出的任何异常在api网关500错误,除非你故意改变其行为,这使得它更难跟踪是怎么回事。

您的代码是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.

相关内容

最新更新