如何使用Java统计S3存储桶中的对象总数?

问题描述 投票:0回答:1

我正在尝试找到一种更快的方法来使用 Amazon 的 AWS SDK 对 s3 存储桶中的所有对象进行计数。

private static int getBucketFileCount(AmazonS3 s3, ListObjectsV2Request req) {
   ListObjectsV2Result result;
   int fileCount = 0;
   log.info("Counting s3 files");

   do {
      result = s3.listObjectsV2(req);
      for (S3ObjectSummary objectSummary : result.getObjectSummaries()) {
         fileCount++;
      }
      req.setContinuationToken(result.getNextContinuationToken());

   } while (result.isTruncated() == true);
       return fileCount;
}

但是,这种方法非常慢,我还没有找到正确的方法。我找到了另一个有帮助的答案,但无法准确地弄清楚实现方式。 getObjectSummaries 会获取存储在 S3 Bucket 中的对象的数量吗?

如何在当前的实现中使用 getNextMarker() 函数?我需要改变什么?

java amazon-web-services amazon-s3 aws-sdk s3-bucket
1个回答
0
投票

获取 AWS 中某个存储桶的对象数量的一种非常快速且廉价的方法是查看该存储桶的 NumberOfObjects Cloudwatch 指标,我相信该指标至少每天都会发布:

    long offsetInMilliseconds = 1000 * 60 * 60 * 24;
    Date endDate = new Date();
    Date startDate = new Date(endDate.getTime() - offsetInMilliseconds);

    Dimension dimension = new Dimension()
        .withName("BucketName")
        .withValue(bucketName);
    Dimension storageTypeDimension = new Dimension()
        .withName("StorageType")
        .withValue("AllStorageTypes");

    GetMetricStatisticsRequest request = new GetMetricStatisticsRequest()
        .withStartTime(startDate)
        .withEndTime(endDate)
        .withPeriod(86400)
        .withDimensions(dimension, storageTypeDimension)
        .withMetricName("NumberOfObjects")
        .withNamespace("AWS/S3")
        .withStatistics(Statistic.Maximum);

    GetMetricStatisticsResult result = cloudWatch.getMetricStatistics(request);

    if (!result.getDatapoints().isEmpty()) {
        double maximumNumberOfObjects = result.getDatapoints().get(0).getMaximum();
        System.out.println("Maximum number of objects: " + maximumNumberOfObjects);
    } else {
        System.out.println("No data available.");
    }
© www.soinside.com 2019 - 2024. All rights reserved.