如何解决我应该在 AWS Lambda 中使用连接池吗?
我最近使用 lambda 将 API 从 EC2 实例切换到 API 网关。我注意到我在数据库上的 cpu 使用率随后急剧上升。
下面是数据库上活动连接的图像,红色箭头是我从 EC2 切换到 Lambda 时的图像。那里没有新客户添加,因此数据的实际吞吐量保持不变。
我使用的代码与我在 Ec2 实例上托管时使用的代码相同。此代码使用连接池连接到数据库,我不确定这是最好的主意。基本上,当我想在主脚本中查询数据库时,我会调用 query
方法。
从连接池中检索连接供 lambda 函数运行查询,然后在查询结束时释放。
这是一种好方法还是应该在整个 lambda 函数执行过程中始终保持一个连接?自从我迁移到 Lambda 后,T3 介质上的 cpu 使用率几乎达到最大值,我认为这就是问题所在。
// This file is used to get a connection from the MysqL connection pool
// The pool is contained in this file and the function to get a connection is exported
// Imports //
const MysqL = require('MysqL')
// Define the connection pool //
const pool = MysqL.createPool({
host: process.env.DBHOST,user: process.env.DBUSER,password: process.env.DBPASSWORD,port: process.env.DBPORT,database: process.env.dbnAME
})
/// getConnection ///
// Call this function whereever you need a connection
// It gets a connection from the connection pool
function getConnection(){
return new Promise((resolve,reject) => {
pool.getConnection((err,con) => {
if(err){
reject(`Connection Failed\n${err}`);
}else{
console.info(`Successful connection,id ${con.threadId}`)
resolve(con)
}
})
})
}
/// query ///
// This function makes a query on a database
// It accepts and sql statement and a list of args if used in the statemens
// Inputs:
// sql - The sql statement to execute on the database
// args - The arguments to use in the sql statament
// Returns:
// resolve - The result of the sql insert statemen
// reject - An error
async function query(sql,args){
return new Promise(async(resolve,reject) => {
// try/catch is to handle the await for the connection
try{
let con = await getConnection() // If there is an error here it will be caught
// No error this query will execute
con.query(sql,args,function(err,result) {
// If error returned from query will be caught here
if (err){
reject(err);// Reject the promise
}else{
resolve(result);// Resolve the promise
}
// Always release
con.release()
})
}catch(error){
// Error in getting connection reject the error
reject(error)
}
})
}
module.exports = {query}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。