使用Lambda的连接池和资源重用功能来减少连接时的开销和延迟。在每个函数的执行结束时,释放数据库连接。
使用pg-promise库的内置连接池来管理数据库连接,以减少连接时的开销和延迟。可以设置连接池的大小,并在需要的时候获取连接。
考虑将数据库连接和查询移动到异步方法或后台任务中,以减少对请求响应时间的影响。
示例代码1:使用Lambda连接池
const AWS = require('aws-sdk');
const pg = require('pg');
const pool = new pg.Pool({
host: ,
user: ,
password: ,
database: ,
port: ,
});
exports.handler = async (event) => {
const client = await pool.connect();
try {
// Do database query here
return {
statusCode: 200,
body: JSON.stringify(result),
};
} finally {
client.release();
}
};
示例代码2:使用pg-promise库的连接池
const pgp = require('pg-promise')();
const db = pgp({
host: ,
user: ,
password: ,
database: ,
port: ,
max: 20, // max number of connections
});
exports.handler = async (event) => {
try {
const result = await db.query('SELECT * FROM my_table');
return {
statusCode: 200,
body: JSON.stringify(result),
};
} finally {
await db.$pool.end(); // release all the connections
}
};
示例代码3:将数据库连接和查询移动到异步方法中
const AWS = require('aws-sdk');
const pg = require('pg');
exports.handler = async (event) => {
const queryPromise = new Promise((resolve, reject) => {
const client = new pg.Client({
host