初始化 DynamoDB 实例 (Lambda + NodeJS) 的最佳位置是什么?

What is the best location to initialise the DynamoDB instance (Lambda + NodeJS)?

我有一个 lambda 层,代码如下:

class PersonModel {
    constructor(tableName, values) {
        // some implementation
    }

    async save() {
        // some implementation

        return docClient.put({
            TableName: this.tableName,
            Item: this.values
        }).promise();
    }
}

在我的 lambdas 实现中,我实例化了 PersonModel 以实现一种 CRUD。是这样的:

exports.handler = async (request) => {
    const person = new PersonModel('profile', { name: 'John' });
    person.save().then(d => {
        return {
            statusCode: 200,
            body: 'Person saved!'
        }
    }).catch(err => {
        return {
            statusCode: 500,
            body: 'Something went wrong!'
        }
    });
};

我的问题:

放置 DocumentClient 实例的最佳位置是什么?

此处(在 js 文件级别):

const docClient = new AWS.DynamoDB.DocumentClient();
class PersonModel {
    constructor(tableName, values) {
        // some implementation
    }
    // etc...

或此处(在对象实现内部 - 它将为每个 lambda 调用创建一个实例):

class PersonModel {
    constructor(tableName, values) {
        // some implementation
        this.docClient = new AWS.DynamoDB.DocumentClient();
    }
    // etc...

还是其他地方更好?

来自 DynamoDB docs:

  • AWS service clients should be instantiated in the initialization code, not in the handler. This allows AWS Lambda to reuse existing connections, for the duration of the container's lifetime.
  • In general, you do not need to explicitly manage connections or implement connection pooling because AWS Lambda manages this for you.

另请注意,某些服务(如 Amazon RDS)具有 limit on the maximum number of open connections,因此如果您曾经使用过此类服务,请牢记这一点。 DynamoDB 不应有任何此类限制。