AWS Lambda:如何使用 java 从 Lambda 函数访问 S3 存储桶

AWS Lambda : How to access S3 bucket from Lambda function using java

我写了一个 Lambda 函数。 这个函数在s3Bucket = "my-lambda"中上传,映射到角色hello-lambda-role和regionName = "us-west-2".

现在我想访问 s3Bucket="some-other" 我们已经将策略映射到 'hello-lambda-role' 并且它位于区域 "eu-west-1".

这里是APIclass我用的是AmazonS3Client。我的目的是从存储桶 "some-other" 中获取一些文件。但在此之前我需要建立连接。

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

public class LambdaFunctionHandler implements RequestHandler<Request, Response> {

    public Response handleRequest(Request request, Context context) {
        String greetingString = String.format("Hello %s %s.",
                request.firstName, request.lastName);
        return new Response(greetingString);
    }

}

这是列出存储桶的 class。

public class Test{
    private static final Log logger = LogFactory.getLog(InvokeLambda.class);
    private static final String awsAccessKeyId = "XXXXX";
    private static final String awsSecretAccessKey = "XXXXX";
    private static final String regionName = "eu-west-1";
    private static Region region;
    private static AWSCredentials credentials;
    private static AWSLambdaClient lambdaClient;
    private static AmazonS3Client s3Client;

    private static void init() {
        credentials = new BasicAWSCredentials(awsAccessKeyId,
                awsSecretAccessKey);
        s3Client = (credentials == null) ? new AmazonS3Client()
                : new AmazonS3Client(credentials);
        region = Region.getRegion(Regions.fromName(regionName));
        s3Client.setRegion(region);
        lambdaClient = (credentials == null) ? new AWSLambdaClient()
                : new AWSLambdaClient(credentials);

        lambdaClient.setRegion(region);
        // lambdaClient.configureRegion(Regions.US_WEST_2);
    }

    /**
     * The entry point into the AWS lambda function.
     */
    public static void main(String... args) {
        init();
        getExistingBucket();
    }

    private static Bucket getExistingBucket() {
        List<Bucket> buckets = s3Client.listBuckets();
        for (Bucket bucket : buckets) {
            logger.error(bucket.getName());
        }
        return null;
    }
}

使用与测试中相同的代码,只是在创建 AmazonS3Client 时不需要提供凭据。请注意,您的 lambda 使用的角色需要有权访问您的 S3 存储桶。 S3 桶的区域无关紧要;存储桶名称唯一标识存储桶,与区域无关。

Lambda 通常由事件触发,但您可以手动调用 AWSLambdaClient.invoke() 到 运行。

例如:

public Response handleRequest(Request request, Context context) {
    AmazonS3Client s3Client = new AmazonS3Client();
    S3Object = s3Client.getObject("some-other", request.getFilename());
    ....
    return new Response(result);
}

将其作为 "mylambda" 部署到 AWS,然后远程调用:

lambdaClient.invoke(new InvokeRequest().withFunctionName("mylambda").withPayload("input"));