我正在使用 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”为 null。 谁能告诉我该怎么做? 此外,因为我无法关闭连接,所以我的控制台每 60 秒就会出现此警告:
8351167 [java-sdk-http-connection-reaper] DEBUG org.apache.http.impl.conn.PoolingClientConnectionManager - Closing connections idle longer than 60 SECONDS
最佳答案
如果你使用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 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();
}
}
关于java - 如果查询中没有这样的键,如何关闭 AWS 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20233259/