我正在尝试使用Amazon S3 JAVA sdk获取文件大小(内容长度)。
public Long getObjectSize(AmazonS3Client amazonS3Client, String bucket, String key)
throws IOException {
Long size = null;
S3Object object = null;
try {
object = amazonS3Client.getObject(bucket, key);
size = object.getObjectMetadata().getContentLength();
} finally {
if (object != null) {
//object.close();
1. This results in 50 calls (connection pool size) post that I start getting connection pool errors.
2. If this line is uncommented it takes hell lot of time to make calls.
}
}
return size;
}
答案 0 :(得分:9)
我猜你的实际问题是什么,但我认为你可以通过做类似的事情来减少代码并消除创建s3Object的需要:
public Long getObjectSize(AmazonS3Client amazonS3Client, String bucket, String key)
throws IOException {
return amazonS3Client.getObjectMetadata(bucket, key).getContentLength();
}
这样就不需要调用您似乎遇到问题的object.close()
。
答案 1 :(得分:0)
对于 Amazon S3 Java SDK 的 v2,请尝试以下操作:
HeadObjectRequest headObjectRequest =
HeadObjectRequest.builder()
.bucket(bucket)
.key(key)
.build();
HeadObjectResponse headObjectResponse =
s3Client.headObject(headObjectRequest);
Long contentLength = headObjectResponse.contentLength();