【发布时间】: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() 方法中?
【问题讨论】:
-
Lambda 执行上下文可以被重用于进一步的执行,看看docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html 所以如果你需要释放资源我想达到它的最好方法是在你的lambda 代码。
标签: java amazon-web-services aws-lambda resource-management