【发布时间】: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