簡體   English   中英

Java 堆空間不足以在 AWS S3 上上傳文件

[英]Java Heap Space is insufficient to upload files on AWS 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() ,因為:

..如果沒有提供,庫將不得不緩沖輸入流的內容以便計算它。

(..可以預見,這將導致“足夠大”的文件出現 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));
 // ...

您需要添加示例代碼以獲得正確的答案。 如果處理大對象,使用TransferManager上傳而不是做putObject。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM