Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? Usinx SDK 1.x, I can do so using the following:

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? 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?

like image 428
simon Avatar asked Dec 17 '18 17:12

simon


People also ask

Does Lambda come with AWS SDK?

By default, the Node. js Lambda runtime environment provides you with a version of the AWS JavaScript SDK.

How AWS Lambda invoke SDK?

You can invoke a Lambda function by creating an AWSLambda object and invoking its invoke method. Create an InvokeRequest object to specify additional information such as the function name and the payload to pass to the Lambda function.


1 Answers

S3Event is part of the AWS Lambda Java Events library where Context is part of the AWS Lambda Java Core. When you include the events library you do pull in the 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. 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. In effect, you're doing the serialization of the S3Event in your code instead of having the Amazon library do it.

Obviously the biggest downside is that you have to serialize the event yourself. An example S3 event in JSON can be found here.

The above example uses JsonPath to pull out, in this case, the keys from the event. You'll be amazed how much smaller your Lambda code is after you remove the Lambda Events library.

like image 108
stdunbar Avatar answered Oct 28 '22 15:10

stdunbar