【问题标题】:Release of resources in AWS LambdaAWS Lambda 中的资源释放
【发布时间】:2018-10-12 08:56:03
【问题描述】:

我使用 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() 方法中?

【问题讨论】:

标签: java amazon-web-services aws-lambda resource-management


【解决方案1】:

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

保持活动状态并重用之前的连接(HTTP、数据库等) 在上一次调用期间建立。

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-24
    • 2012-01-08
    • 2012-05-04
    • 2018-11-20
    • 2016-07-01
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多