这就是我们的目标。
jist在每个lambda开始之前创建一个新连接,然后在从lambda返回之前关闭它
// your lambda entry point module.exports.handler = (event, context, callback) => getConnection(async (connection) => { let result; try { // work with your connection } catch (error) { } callback(null, result); }) // db connection const getConnection = async (callback) => { const dbConnection = new DBConnection(); try { const connection = await dbConnection.create(); await callback(connection); } finally { dbConnection.close(); } }; const MAX_RETRY = 3; const options = { // global event notification; error: (error, e) => { if (e.cn) { // A connection-related error; // // Connections are reported back with the password hashed, // for safe errors logging, without exposing passwords. logger.error('CN:', e.cn); logger.error('EVENT:', error.message || error); } }, }; const pgp = require('pg-promise')(options); const connectionParams = { host: process.env.DATABASE_HOST, port: process.env.DATABASE_PORT, database: process.env.DATABASE_NAME, user: process.env.DATABASE_USERNAME, password: process.env.DATABASE_PASSWORD, poolSize: 0, poolIdleTimeout: 10, }; const db = pgp(connectionParams); class DBConnection { async create() { let retry = 0; while (retry < MAX_RETRY) { try { logger.debug(`Acquiring a new DB connection Attempt: ${retry}/${MAX_RETRY}`); this.connection = await db.connect({ direct: true }); break; } catch (error) { logger.error(`Error occurred while getting DB connection ${error}. Retrying ${retry}/${MAX_RETRY}`); retry += 1; } } if (!this.connection) { throw Error(`Unable to obtain DB connection after ${MAX_RETRY} retries`); } return this.connection; } close() { if (this.connection) { logger.debug('Closing DB Connection'); this.connection.done(); } } }
我们如何发布连接?
你没有。连接自动与连接池通信。一旦查询结束执行,连接就会返回到池中,以供下一个请求它的查询使用。
一次执行多个查询时,您应该使用任务。看到 链接查询 。
我们如何重试获得新连接?
根据连接需求和最大池大小,连接池会在必要时自动创建新的物理连接。当连接断开时,会自动重新创建。
如果您在AWS lambda中拥有单一连接,那么最好的模式可能是创建和维护单个全局连接吗?
如果是这样的话,那就是 健壮的听众 例子可能对你有用。它显示了如何在连接池之外维护单个全局连接,以及如何使其始终保持活动状态。
但这更像是最后的手段。我相信只需使用自动连接池就足够了。