除非我遗漏了什么,否则我所看过的所有api似乎都不会告诉您<S3 bucket>/<文件夹>中有多少对象。有办法统计一下吗?


当前回答

以下是如何使用java客户端。

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-s3</artifactId>
    <version>1.11.519</version>
</dependency>
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectListing;

public class AmazonS3Service {

    private static final String S3_ACCESS_KEY_ID = "ACCESS_KEY";
    private static final String S3_SECRET_KEY = "SECRET_KEY";
    private static final String S3_ENDPOINT = "S3_URL";

    private AmazonS3 amazonS3;

    public AmazonS3Service() {
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setProtocol(Protocol.HTTPS);
        clientConfiguration.setSignerOverride("S3SignerType");
        BasicAWSCredentials credentials = new BasicAWSCredentials(S3_ACCESS_KEY_ID, S3_SECRET_KEY);
        AWSStaticCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
        AmazonS3ClientBuilder.EndpointConfiguration endpointConfiguration = new AmazonS3ClientBuilder.EndpointConfiguration(S3_ENDPOINT, null);
        amazonS3 = AmazonS3ClientBuilder.standard().withCredentials(credentialsProvider).withClientConfiguration(clientConfiguration)
                .withPathStyleAccessEnabled(true).withEndpointConfiguration(endpointConfiguration).build();
    }

    public int countObjects(String bucketName) {
        int count = 0;
        ObjectListing objectListing = amazonS3.listObjects(bucketName);
        int currentBatchCount = objectListing.getObjectSummaries().size();
        while (currentBatchCount != 0) {
            count += currentBatchCount;
            objectListing = amazonS3.listNextBatchOfObjects(objectListing);
            currentBatchCount = objectListing.getObjectSummaries().size();
        }
        return count;
    }
}

其他回答

选择桶/文件夹->单击动作->单击计算总大小

没有办法,除非你

以1000个为一组列出它们(这可能很慢,而且占用带宽——amazon似乎从不压缩XML响应),或者 在S3上登录您的帐户,然后进入帐户-使用。似乎账单部门确切地知道你存储了多少对象!

如果您存储了5000万个对象,那么仅仅下载所有对象的列表实际上就需要花费一些时间和金钱。

也可以看到这个关于StorageObjectCount的线程——它在使用数据中。

一个S3 API至少能获得基础知识,即使它是几个小时以前的,也会很棒。

有一个——summary开关,显示桶的摘要信息(即对象的数量,总大小)。

下面是使用AWS cli的正确答案:

aws s3 ls s3://bucketName/path/ --recursive --summarize | grep "Total Objects:"

Total Objects: 194273

参见文档

在AWS CLI的命令行中,使用ls加——summary。它将为您提供所有项目的列表以及特定bucket中的文档总数。我还没有尝试过包含子桶的桶:

aws s3 ls "s3://MyBucket" --summarize

这可能会花费一些时间(列出我16+K的文档大约需要4分钟),但这比一次计算1K要快。

api将以1000为增量返回列表。检查IsTruncated属性,看看是否还有更多。如果有,您需要进行另一次调用,并在下次调用时传递您获得的最后一个键作为Marker属性。然后继续这样循环,直到IsTruncated为false。

有关更多信息,请参阅亚马逊文档:遍历多页结果