如何在 aws lambda 中关闭 aws 客户端

How to close aws client in aws lambda

我正在尝试使用 Java 正确编写 aws lambda,它将使用 aws sdk SqsClient 和 SnsClient。我看到这些客户端实现了 close() 方法,当不再需要客户端时调用此方法通常是一个好习惯。 lambda (https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html) 的最佳实践建议

Initialize SDK clients and database connections outside of the function handle

所以,我的问题是:aws lambda 是否足够明智地自动关闭 aws sdk 客户端,这样我就可以写这样的东西,而不用担心在 lambda 容器关闭时显式关闭客户端。

public class SQSProcessingHandler implements RequestHandler<String, String> {

    private SqsClient sqsClient = SqsClient.create();

    @Override
    public String handleRequest(final String event, final Context context) {
        ListQueuesResponse response = sqsClient.listQueues();
        return response.queueUrls().stream().collect(Collectors.joining(","));
    }
}

如果仍然需要显式关闭,你能帮我看看我怎么知道lambda容器即将关闭,所以我应该在客户端调用close()吗?

为获得最佳实践,您应该明确关闭客户端,除非您有理由不这样做。

Service clients in the SDK are thread-safe. For best performance, treat them as long-lived objects. Each client has its own connection pool resource that is released when the client is garbage collected. The clients in the AWS SDK for Java 2.0 now extend the AutoClosable interface. For best practices, explicitly close a client by calling the close method.

不明确关闭客户端的原因:

为获得最佳性能,请勿显式关闭客户端。这是因为未关闭的客户端在打开后通过保留在可重用连接池中来维护与服务的套接字。因此,当再次调用 lambda 时,客户端可能会被重用。 Lambda 可以并且将在稍后自动为您关闭客户端,即使您没有明确关闭它。

参考:https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/creating-clients.html