Java 堆空间不足以在 AWS S3 上上传文件

Wic*_*mon 4 java amazon-s3 amazon-web-services spring-boot

我正在尝试使用 Java-AWS API 在 AWS S3 上上传文件。问题是我的应用程序无法上传大型文件,因为堆已达到其限制。错误:java.lang.OutOfMemoryError:Java 堆空间

我个人认为扩展堆内存不是永久的解决方案,因为我必须将文件上传到 100 GB。我该怎么办 ?

这是代码片段:

        BasicAWSCredentials awsCreds = new BasicAWSCredentials(AID, Akey);
        AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
        .withRegion(Regions.fromName("us-east-2"))
        .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
        .build();

        InputStream Is=file.getInputStream();

        boolean buckflag = s3Client.doesBucketExist(ABuck);
        if(buckflag != true){
           s3Client.createBucket(ABuck);
        }
        s3Client.putObject(new PutObjectRequest(ABuck, AFkey,file.getInputStream(),new ObjectMetadata() ).withCannedAcl(CannedAccessControlList.PublicRead));
Run Code Online (Sandbox Code Playgroud)

xer*_*593 8

我强烈推荐setContentLength()on ObjectMetadata,因为:

..如果没有提供,库将不得不缓冲输入流的内容以便计算它。

(..可以预见,这将导致“足够大”的文件出现 OutOfMemory。)

来源:PutObjectRequest javadoc

应用于您的代码:

 // ...
 ObjectMetadata omd = new ObjectMetadata();
 // a tiny code line, but with a "huge" information gain and memory saving!;)
 omd.setContentLength(file.length());

 s3Client.putObject(new PutObjectRequest(ABuck, AFkey, file.getInputStream(), omd).withCannedAcl(CannedAccessControlList.PublicRead));
 // ...
Run Code Online (Sandbox Code Playgroud)