简体   繁体   中英

Release of resources in AWS Lambda

I implement AWS Lambda function with Java and face with the question - how to release used resources correctly? In my function I make different calls of some resources: execute queries to DB, make REST-calls to third-party services (send StatsD metrics, invoke Slack webhooks, etc), interact with Kinesys stream.

Not going into details, my function looks like this:

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
         */
    }
}

And my main question is - where is more correctly release resources which are used in my services, in the end of handleRequest() method (in such case I'll need to open them all again in each next invocation of Lambda-function) or in finalize() method of RequestHandler class?

According to Lambda best practices you should :

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

So your current code is right.

Regarding the finalize() function, I don't think it is relevant. Lambda execution context will be deleted at some point freeing automatically every open resources.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM