AWS Lambda 资源释放

Release of resources in AWS Lambda

我用 Java 实现了 AWS Lambda 函数并面临问题 - 如何正确释放使用的资源?在我的函数中,我对一些资源进行了不同的调用:对数据库执行查询,对第三方服务进行 REST 调用(发送 StatsD 指标,调用 Slack webhook 等),与 Kinesys 流交互。

不细说了,我的函数是这样的:

public class RequestHandler {
    private StatisticsService statsService;         //Collect StatsD metrics
    private SlackNotificationService slackService;  //Send Slack notifications
    private SearchService searchService;            //Interact with DB

    //Simplified version of constructor
    public RequestHandler() {
        this.statsService = new StatisticsService();
        this.slackService = new SlackNotificationService();
        this.searchService = new SearchService();
    }

    public LambdaResponse handleRequest(LambdaRequest request, Context context) {
        /**
         * Main method of function
         * where business-logic is executed
         * and all mentioned services are invoked
         */
    }
}

我的主要问题是 - 在 handleRequest() 方法的末尾,在哪里更正确地释放我的服务中使用的资源(在这种情况下,我需要在每次下一次调用时再次打开它们Lambda 函数)或在 RequestHandler 的 finalize() 方法中 class?

根据 Lambda 最佳实践,您应该:

Keep alive and reuse connections (HTTP, database, etc.) that were established during a previous invocation.

所以您当前的代码是正确的。

关于 finalize() 函数,我认为它不相关。 Lambda 执行上下文将在某个时候删除,自动释放每个打开的资源。

https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html#function-code