How to close AWS connection if there is no such key in the query

天涯浪子 提交于 2020-01-02 11:30:23

问题


I'm using AWS java SDK to upload file on AWS Management Console's Bucket. However, if there is no such file online at first time when I try to get access to it, my code will catch the exception (NoSuchKey). Then I want to close the connection. The problem is I don't have any reference to close that connection because of the exception(The original reference will be null). Here is my code:

    S3Object object = null;
    GetObjectRequest req = new GetObjectRequest(bucketName, fileName);

    try{
        logconfig();

        object = s3Client.getObject(req);
                  ...
    catch(AmazonServiceException e){
        if(e.getErrorCode().equals("NoSuchKey"))

I was trying to use "object" as a reference to close the connection between my eclipse and Aws, but apparently "object" is null when the exception happened. Can anyone tell me how to do it? Furthermore, because I can't close the connection, my console will have this warning every 60 seconds:

8351167 [java-sdk-http-connection-reaper] DEBUG org.apache.http.impl.conn.PoolingClientConnectionManager  - Closing connections idle longer than 60 SECONDS

回答1:


If you use Java 1.7, you can use try-with-resouce block. The object will be closed automatically when leaving the block.

GetObjectRequest req = new GetObjectRequest(bucketName, fileName);
try(S3Object object = s3Client.getObject(req)) {
    ...
} catch(AmazonServiceException e) {
    if(e.getErrorCode().equals("NoSuchKey"));
}

If you use Java 1.6 or prior version, you need to do it in finally block

S3Object object = null;
GetObjectRequest req = new GetObjectRequest(bucketName, fileName);
try {
    object = s3Client.getObject(req))
    ...
} catch(AmazonServiceException e) {
    if(e.getErrorCode().equals("NoSuchKey"));
} finally {
    if (object != null) {
        object.close();
    }
}


来源:https://stackoverflow.com/questions/20233259/how-to-close-aws-connection-if-there-is-no-such-key-in-the-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!