【问题标题】:How to close AWS connection if there is no such key in the query如果查询中没有这样的键,如何关闭 AWS 连接
【发布时间】:2017-02-23 08:14:15
【问题描述】:

我正在使用 AWS java SDK 在 AWS 管理控制台的存储桶上上传文件。但是,如果第一次尝试访问它时没有这样的文件在线,我的代码将捕获异常(NoSuchKey)。然后我想关闭连接。问题是我没有任何参考来关闭该连接,因为异常(原始参考将为空)。这是我的代码:

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

    try{
        logconfig();

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

我试图使用“object”作为参考来关闭我的 eclipse 和 Aws 之间的连接,但是当异常发生时,显然“object”为空。 谁能告诉我该怎么做? 此外,由于我无法关闭连接,我的控制台将每 60 秒出现一次警告:

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

【问题讨论】:

  • 我认为您不需要自己进行任何连接处理。这是图书馆的照顾。你只需要调用s3client中的API。
  • 如果对象实现了 Closable(),你应该调用 close()。否则可能会发生资源泄漏。

标签: java amazon-web-services amazon-s3 sdk aws-sdk


【解决方案1】:

如果您使用 Java 1.7,则可以使用 try-with-resouce 块。离开方块时物体会自动关闭。

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

如果你使用Java 1.6或之前的版本,需要在finally块中进行

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();
    }
}

【讨论】:

    猜你喜欢
    • 2016-08-28
    • 2015-06-18
    • 1970-01-01
    • 2021-01-23
    • 2013-04-04
    • 2022-01-02
    • 2021-12-21
    • 2015-12-21
    相关资源
    最近更新 更多