简体   繁体   English

如何使用AWS SDK for Java 2.0创建Lambda函数

[英]How to create a Lambda function using AWS SDK for Java 2.0

How do one create a Lambda function using AWS SDK for Java 2.0? 如何使用AWS SDK for Java 2.0创建Lambda函数? Usinx SDK 1.x, I can do so using the following: Usinx SDK 1.x,我可以使用以下方法:

public String handleRequest(S3Event s3event, Context context) {
System.out.println("do stuff");
return "success";
}

Using java SDK 2.x, I can't seem to find the equivalent dependencies for S3Event and Context object? 使用java SDK 2.x,我似乎无法找到S3Event和Context对象的等效依赖项? I would really appreciate if someone could point me to examples. 如果有人能指出我的例子,我真的很感激。 Or should I just stick to using SDK 1.x if 2.x is not mature enough for handling lambda? 或者我应该坚持使用SDK 1.x如果2.x还不够成熟以处理lambda?

S3Event is part of the AWS Lambda Java Events library where Context is part of the AWS Lambda Java Core . S3EventAWS Lambda Java事件库的一部分,其中ContextAWS Lambda Java Core的一部分 When you include the events library you do pull in the 1.x Java SDK. 当您包含事件库时,您需要引入1.x Java SDK。 However, if you use the Java Stream version of the Lambda handler you can remove the dependency to the events library and thus remove your need for the 1.x SDK. 但是,如果您使用Lambda处理程序的Java Stream版本,则可以删除对事件库的依赖性,从而消除对1.x SDK的需求。 Your code would look something like: 您的代码看起来像:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import com.jayway.jsonpath.JsonPath;


public class S3EventLambdaHandler implements RequestStreamHandler {
    public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) {

        try {
            List<String> keys = JsonPath.read(inputStream, "$.Records[*].s3.object.key");

            for( String nextKey: keys )
                System.out.println(nextKey);
        }
        catch( IOException ioe ) {
            context.getLogger().log("caught IOException reading input stream");
        }
    }
}

then you can read the JSON that is in the S3Event yourself. 那么你可以自己阅读S3Event中的JSON。 In effect, you're doing the serialization of the S3Event in your code instead of having the Amazon library do it. 实际上,您正在代码中对S3Event进行序列化,而不是让Amazon库执行此操作。

Obviously the biggest downside is that you have to serialize the event yourself. 显然最大的缺点是你必须自己序列化事件。 An example S3 event in JSON can be found here . 可以在此处找到JSON中的示例S3事件。

The above example uses JsonPath to pull out, in this case, the keys from the event. 上面的示例使用JsonPath在这种情况下从事件中提取键。 You'll be amazed how much smaller your Lambda code is after you remove the Lambda Events library. 删除Lambda事件库后,您会惊讶地发现Lambda代码的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM