Java 堆空间不足,无法在 AWS S3 上上传文件

标签 java amazon-web-services spring-boot amazon-s3

我正在尝试使用 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));

最佳答案

我强烈建议在 ObjectMetadata 上使用 setContentLength(),因为:

..If not provided, the library will have to buffer the contents of the input stream in order to calculate it.

(..这可以预见会导致“足够大”的文件出现 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));
 // ...

关于Java 堆空间不足,无法在 AWS S3 上上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54379555/

相关文章:

java - 如何在 Spring Portlet MVC 中获取对象类型参数

ios - 从 Amazon S3 下载图像(使用 AWS mobile hub helper)

python - 限制我的程序通过 SQS 发送过多 SES 电子邮件的速率

java - 如何在启动时设置默认@AuthenticationPrincipal

java - 调用方法而不启动 UI

java - 为什么我的字段是空的,即使它应该立即实例化?

java - 优化 Android 中的 HttpURLConnection

android - 来自 Android 的所有 S3 调用都出现 504 错误

spring-boot - 将 Spring Cloud Contract Stub Runner 与手动创建的 stub 结合使用

java - 如何在 Spring boot 1.5.2 中终止 Hibernates 数据库连接?