我使用 Java 实现 AWS Lambda 函数并面临一个问题 - 如何正确释放使用过的资源?在我的函数中,我对一些资源进行了不同的调用:对数据库执行查询,对第三方服务进行 REST 调用(发送 StatsD 指标,调用 Slack webhooks 等),与 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 最佳实践,您应该:
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
关于java - 在 AWS Lambda 中释放资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50131403/