如何从用 Java 编写的 AWS Lambda 函数读取 S3 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36462933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:29:06  来源:igfitidea点击:

How to read S3 file from AWS Lambda Function written in Java?

javaamazon-web-servicesamazon-s3aws-lambda

提问by Sumit Arora

I have written a AWS Lambda Function, Its objective is that on invocation - it read the contents of a file say x.db, get a specific value out of it and return to the caller.But this x.db file changes time to time. So I would like to upload this x.db file to S3 and read it from AWS Lambda function as like reading a file.

我编写了一个 AWS Lambda 函数,它的目标是在调用时 - 它读取文件的内容,比如 x.db,从中获取特定值并返回给调用者。但是这个 x.db 文件会不时更改. 所以我想将此 x.db 文件上传到 S3 并从 AWS Lambda 函数中读取它,就像读取文件一样。

        File xFile = new File("S3 file in x.db");

How to read such x.db S3 file from AWS Lambda Function written in Java ?

如何从用 Java 编写的 AWS Lambda 函数读取这样的 x.db S3 文件?

回答by ataylor

Use the Java S3 SDK. If you upload a file called x.dbto an S3 bucket mybucket, it would look something like this:

使用 Java S3 SDK。如果您上传一个名为x.dbS3 存储桶的文件mybucket,它将如下所示:

import com.amazonaws.services.s3.*;
import com.amazonaws.services.s3.model.*;

...
AmazonS3 client = new AmazonS3Client();
S3Object xFile = client.getObject("mybucket", "x.db");
InputStream contents = xFile.getObjectContent();

In addition, you should ensure the role you've assigned to your lambda function has access to the S3 bucket. Apply a policy like this:

此外,您应该确保分配给 lambda 函数的角色可以访问 S3 存储桶。应用这样的策略:

"Version": "2012-10-17",
"Statement": [{
  "Effect": "Allow",
  "Action": [
    "s3:*"
  ],
  "Resource": [
    "arn:aws:s3:::mybucket",
    "arn:aws:s3:::mybucket/*"
  ]
}]