为什么不在代码中关闭S3客户端?

huangapple go评论60阅读模式
英文:

Why not shutdown the s3 client in the code?

问题

我正在寻找 AWS SDK 指南文档。

以下代码解释了 AWS SDK 中 S3 的使用方式。

在 finally 子句中,我看不到对 S3 客户端 的关闭操作。
它具有释放所占资源的 shutdown 方法。
但在官方文档中没有看到关闭资源的操作。

我的假设正确吗?还是我漏掉了其他什么事情?

public class GetObject2 {

    public static void main(String[] args) throws IOException {
        Regions clientRegion = Regions.DEFAULT_REGION;
        String bucketName = "*** Bucket name ***";
        String key = "*** Object key ***";

        S3Object fullObject = null, objectPortion = null, headerOverrideObject = null;
        try {
            AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                    .withRegion(clientRegion)
                    .withCredentials(new ProfileCredentialsProvider())
                    .build();

            // 获取对象并打印其内容。
            System.out.println("下载对象");
            fullObject = s3Client.getObject(new GetObjectRequest(bucketName, key));
            System.out.println("Content-Type: " + fullObject.getObjectMetadata().getContentType());
            System.out.println("内容:");
            displayTextInputStream(fullObject.getObjectContent());

            // 获取对象的一部分字节并打印字节。
            GetObjectRequest rangeObjectRequest = new GetObjectRequest(bucketName, key)
                    .withRange(0, 9);
            objectPortion = s3Client.getObject(rangeObjectRequest);
            System.out.println("打印检索的字节。");
            displayTextInputStream(objectPortion.getObjectContent());

            // 获取整个对象,覆盖指定的响应标头,并打印对象的内容。
            ResponseHeaderOverrides headerOverrides = new ResponseHeaderOverrides()
                    .withCacheControl("No-cache")
                    .withContentDisposition("attachment; filename=example.txt");
            GetObjectRequest getObjectRequestHeaderOverride = new GetObjectRequest(bucketName, key)
                    .withResponseHeaders(headerOverrides);
            headerOverrideObject = s3Client.getObject(getObjectRequestHeaderOverride);
            displayTextInputStream(headerOverrideObject.getObjectContent());
        } catch (AmazonServiceException e) {
            // 调用已成功传输,但 Amazon S3 无法处理
            // 它,因此返回了错误响应。
            e.printStackTrace();
        } catch (SdkClientException e) {
            // 无法联系 Amazon S3 以获取响应,或者客户端
            // 无法解析 Amazon S3 的响应。
            e.printStackTrace();
        } finally {
            // 为确保网络连接不保持打开状态,请关闭任何打开的输入流。
            if (fullObject != null) {
                fullObject.close();
            }
            if (objectPortion != null) {
                objectPortion.close();
            }
            if (headerOverrideObject != null) {
                headerOverrideObject.close();
            }
        }
    }

    private static void displayTextInputStream(InputStream input) throws IOException {
        // 逐行读取文本输入流并显示每行。
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        System.out.println();
    }
}
英文:

I am looking for the aws sdk guide documentation.

Below code explains the s3 usage for aws sdk.

In the finally clause, I cannot see the shutdown for the S3 client.
It has shutdown method for releasing the resource it held.
But the closing the resources cannot be seen in the official document.

My assumption is correct? Or is there any other thing that I have missed?

public class GetObject2 {
public static void main(String[] args) throws IOException {
Regions clientRegion = Regions.DEFAULT_REGION;
String bucketName = "*** Bucket name ***";
String key = "*** Object key ***";
S3Object fullObject = null, objectPortion = null, headerOverrideObject = null;
try {
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withRegion(clientRegion)
.withCredentials(new ProfileCredentialsProvider())
.build();
// Get an object and print its contents.
System.out.println("Downloading an object");
fullObject = s3Client.getObject(new GetObjectRequest(bucketName, key));
System.out.println("Content-Type: " + fullObject.getObjectMetadata().getContentType());
System.out.println("Content: ");
displayTextInputStream(fullObject.getObjectContent());
// Get a range of bytes from an object and print the bytes.
GetObjectRequest rangeObjectRequest = new GetObjectRequest(bucketName, key)
.withRange(0, 9);
objectPortion = s3Client.getObject(rangeObjectRequest);
System.out.println("Printing bytes retrieved.");
displayTextInputStream(objectPortion.getObjectContent());
// Get an entire object, overriding the specified response headers, and print the object's content.
ResponseHeaderOverrides headerOverrides = new ResponseHeaderOverrides()
.withCacheControl("No-cache")
.withContentDisposition("attachment; filename=example.txt");
GetObjectRequest getObjectRequestHeaderOverride = new GetObjectRequest(bucketName, key)
.withResponseHeaders(headerOverrides);
headerOverrideObject = s3Client.getObject(getObjectRequestHeaderOverride);
displayTextInputStream(headerOverrideObject.getObjectContent());
} catch (AmazonServiceException e) {
// The call was transmitted successfully, but Amazon S3 couldn't process 
// it, so it returned an error response.
e.printStackTrace();
} catch (SdkClientException e) {
// Amazon S3 couldn't be contacted for a response, or the client
// couldn't parse the response from Amazon S3.
e.printStackTrace();
} finally {
// To ensure that the network connection doesn't remain open, close any open input streams.
if (fullObject != null) {
fullObject.close();
}
if (objectPortion != null) {
objectPortion.close();
}
if (headerOverrideObject != null) {
headerOverrideObject.close();
}
}
}
private static void displayTextInputStream(InputStream input) throws IOException {
// Read the text input stream one line at a time and display each line.
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
System.out.println();
}
}

答案1

得分: 2

shutdown() 方法的描述来自于 SDK 文档 中的 AmazonS3 类:

关闭此客户端对象,释放可能保持打开状态的任何资源。这是一个可选方法,不需要调用者调用它,但如果他们想要显式释放任何打开的资源,可以调用它。一旦客户端被关闭,就不应再用于发出任何更多的请求。

对 S3 的请求是通过单独的 REST API 调用完成的,因此客户端不像你从数据库客户端中期望的那样维护连续的连接/会话。它只是使用提供给它的配置数据构建并签署每个请求。这可能是为什么调用 shutdown 方法对于 S3 客户端不那么重要的原因。

英文:

Description of shutdown() from the SDK documentation for AmazonS3 class:

> Shuts down this client object, releasing any resources that might be held open. This is an optional method, and callers are not expected to call it, but can if they want to explicitly release any open resources. Once a client has been shutdown, it should not be used to make any more requests.

Requests to S3 are done via individual REST API calls, so the client doesn't maintain a continuous connection/session as you'd expect from a database client for example. It simply constructs and signs each request using the configuration data provided to it. This is probably why calling the shutdown method is not as important for the S3 client.

huangapple
  • 本文由 发表于 2023年1月9日 01:15:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75049832.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定