我用Java实现了AWS函数,并回答了这个问题--如何正确地释放使用过的资源?在我的函数中,我对一些资源进行了不同的调用:对DB执行查询,对第三方服务进行REST调用(发送StatsD度量,调用等),与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()方法中,哪里更正确地释放了在服务中使用的资源?
发布于 2018-05-02 10:11:05
根据Lambda的最佳实践,您应该:
保持活动并重用连接(HTTP、数据库等)在上一次调用期间建立的。
所以你现在的代码是对的。
关于finalize()函数,我不认为它是相关的。Lambda执行上下文将在某个时候被删除,自动释放每个打开的资源。
https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html#function-code
https://stackoverflow.com/questions/50131403
复制相似问题