2016-04-29 370 views
2

我正在創建每月運行的AWS Lambda函數。每個月處理一些數據並將其寫回S3 Bucket。AWS Lambda Java,寫入S3存儲桶

您是否知道如何從AWS Lambda Java將文件寫入S3存儲桶?

回答

1

與從任何Java應用程序向S3寫入文件的方式相同。使用AWS SDK for Java

0

我會建議使用AWS Kinesis FireHose服務,允許從AWS SDK作爲字符串發送數據。 該服務將爲您寫入文件,聚合事件,甚至用時間戳壓縮文件。

+2

室壁運動似乎矯枉過正我剛剛發佈每月單個文件到S3。爲什麼不只是使用帶有IAM角色的aws SDK連接到您的lambda函數? – Tom

+0

當然,您可以使用SDK從字符串寫入文件。我不知道你有多少數據,這可能是一個問題,將所有內容存儲在內存中,然後作爲文件轉儲。 –

0

試試這個:

try{ 
      // Create new file 
      Util._logger.log(" Creating file transfer "); 

      StringBuilder stringBuilder = new StringBuilder(); 

      //Writing in file 
      stringBuilder.append('Data you want to write in file'); 

      // Upload file 
      ByteArrayInputStream inputStream = new ByteArrayInputStream(stringBuilder.toString().getBytes(Constants.UTF_8)); 
      s3Client.putObject(dstBucket, uploadFileName, inputStream, new ObjectMetadata()); 

     } catch (UnsupportedEncodingException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (AmazonServiceException ase) { 
      System.out.println("Caught an AmazonServiceException, " + 
        "which means your request made it " + 
        "to Amazon S3, but was rejected with an error " + 
        "response for some reason."); 
      System.out.println("Error Message: " + ase.getMessage()); 
      System.out.println("HTTP Status Code: " + ase.getStatusCode()); 
      System.out.println("AWS Error Code: " + ase.getErrorCode()); 
      System.out.println("Error Type:  " + ase.getErrorType()); 
      System.out.println("Request ID:  " + ase.getRequestId()); 
      Util._logger.log(Constants.EXCEPTION_ERROR + ase.getMessage()); 
      ase.printStackTrace(); 
     } catch (AmazonClientException ace) { 
       System.out.println("Caught an AmazonClientException, " + 
         "which means the client encountered " + 
         "an internal error while trying to " + 
         " communicate with S3, " + 
         "such as not being able to access the network."); 
       System.out.println(Constants.EXCEPTION_ERROR + ace.getMessage()); 
       Util._logger.log(Constants.EXCEPTION_ERROR + ace.getMessage()); 
       ace.printStackTrace(); 
     } catch (Exception e) { 
       Util._logger.log(Constants.EXCEPTION_ERROR + e.getMessage()); 
       e.printStackTrace(); 
     }