2016-04-29 369 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(); 
     }