如何将大量文件从S3文件夹复制到另一个

时间:2019-05-22 14:30:54

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

我正在尝试将大量文件(每个文件的最大大小约为300Kb)从S3文件夹移动到另一个文件夹。

我正在使用适用于Java的AWS开发工具包,并尝试移动1500个文件。

花了太多时间,文件数量可能增加到10,000。

对于文件的每个副本,由于没有移动文件的方法,因此需要从源文件夹中删除。

这是我尝试过的:

public void moveFiles(String fromKey, String toKey) {
    Stream<S3ObjectSummary> objectSummeriesStream = this.getObjectSummeries(fromKey);
    objectSummeriesStream.forEach(file ->
        {
            this.s3Bean.copyObject(bucketName, file.getKey(), bucketName, toKey);
            this.s3Bean.deleteObject(bucketName, file.getKey());
        });

}

private Stream<S3ObjectSummary> getObjectSummeries(String key) {

    // get the files that their prefix is "key" (can be consider as Folders).
    ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(this.bucketName)
        .withPrefix(key);
    ObjectListing outFilesList = this.s3Bean.listObjects(listObjectsRequest);
    return outFilesList.getObjectSummaries()
        .stream()
        .filter(x -> !x.getKey()
            .equals(key));
}

1 个答案:

答案 0 :(得分:0)

如果您正在使用Java应用程序,则可以尝试使用多个线程来复制文件:

private ExecutorService executorService = Executors.fixed(20);

public void moveFiles(String fromKey, String toKey) {
    Stream<S3ObjectSummary> objectSummeriesStream = 
    this.getObjectSummeries(fromKey);
    objectSummeriesStream.forEach(file ->
    {
        executorService.submit(() ->
            this.s3Bean.copyObject(bucketName, file.getKey(), bucketName, toKey);
            this.s3Bean.deleteObject(bucketName, file.getKey());
        )};
    });

}

这将加快处理过程。

替代方法可能是使用AWS-lambda。一旦文件出现在源存储桶中,您就可以将事件放入SQS FIFO队列中。 Lambda将通过此事件开始单个文件复制。如果我没有误会您可以同时启动多达500个lambda实例。应该很快。