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

时间:2016-01-13 07:17:15

标签: java amazon-web-services amazon-s3 aws-lambda

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

现在我想访问s3Bucket ="其他一些"在哪里我们用' hello-lambda-role'映射了策略。它位于该地区" eu-west-1"。

以下是我使用的AmazonS3Client API类。我的目的是从桶中获取一些文件"其他一些"。但在此之前,我需要建立连接。

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);
    }

}

这是列出存储桶的类。

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;
    }
}

1 个答案:

答案 0 :(得分:11)

使用与测试中相同的代码,但在创建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"));