AWS Lambda With Java

1. Introduction

AWS Lambda is a serverless computing service provided by Amazon to reduce the configuration of servers, OS, Scalability, etc. AWS Lambda is capable of executing code on AWS Cloud.

It runs in response to events on different AWS resources, which triggers AWS Lambda functions. Pricing is pay-as-you-go which means we won’t shell our money on idle lambda functions.

This tutorial requires a valid AWS account; you can create one here.

2. Maven Dependencies

To enable AWS lambda, we need the following dependency in our project:

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-lambda-java-core</artifactId>
    <version>1.1.0</version>
</dependency>

This dependency can be found at Maven repository.

We also need the Maven Shade Plugin to build the lambda application:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>2.4.3</version>
    <configuration>
        <createDependencyReducedPom>false</createDependencyReducedPom>
    </configuration>
    <executions>
        <execution>
            <phase>package</phase>
        <goals>
                <goal>shade</goal>
            </goals>
        </execution>
    </executions>
</plugin>

3. Create Handler

Simply put, to invoke a lambda function, we need to specify a handler; there are 3 ways of creating a handler:

  1. Creating a custom MethodHandler

  2. Implementing the RequestHandler interface

  3. Implementing the RequestStreamHandler interface

Let’s see how to do it using code examples.

3.1. Custom MethodHandler

We’ll create a handler method that will be the entry point for incoming requests. We can use JSON format or primitive data types as input values.

Also, the optional Context object will allow us to access useful information available within the Lambda execution environment:

public class LambdaMethodHandler {
    public String handleRequest(String input, Context context) {
        context.getLogger().log("Input: " + input);
        return "Hello World - " + input;
    }
}

3.2. RequestHandler Interface

We can also implement the RequestHandler into our class and override the handleRequest method which will be our entry point for requests:

public class LambdaRequestHandler
  implements RequestHandler<String, String> {
    public String handleRequest(String input, Context context) {
        context.getLogger().log("Input: " + input);
        return "Hello World - " + input;
    }
}

In this case, the input will be the same as in the first example.

3.3. RequestStreamHandler Interface

We can also implement RequestStreamHandler in our class and simply override the handleRequest method.

The difference is that InputStream, ObjectStream and Context objects are being passed as parameters:

public class LambdaRequestStreamHandler
  implements RequestStreamHandler {
    public void handleRequest(InputStream inputStream,
      OutputStream outputStream, Context context) {
        String input = IOUtils.toString(inputStream, "UTF-8");
        outputStream.write(("Hello World - " + input).getBytes());
    }
}

4. Build Deployment File

With everything configured, we can create the deployment file by simply running:

mvn clean package shade:shade

The jar file will be created under the target folder.

5. Create Lambda Function Via Management Console

Sign in to AWS Amazon and then click on Lambda under services. This page will show the lambda functions list, which is already created.

Here are the steps required to create our lambda:

  1. “Select blueprint” and then select “Blank Function”

  2. “Configure triggers” (in our case we don’t have any triggers or events)

  3. “Configure function”:

    • Name: Provide MethodHandlerLambda,

    • Description: Anything that describes our lambda function

    • Runtime: Select java8

    • Code Entry Type and Function Package: Select “Upload a .ZIP and Jar file” and click on “Upload” button. Select the file which contains lambda code.

    • Under Lambda function handler and role:

      • Handler name: Provide lambda function handler name com.baeldung.MethodHandlerLambda::handleRequest

      • Role name: If any other AWS resources are used in lambda function, then provide access by creating/using existing role and also define the policy template.

    • Under Advanced settings:

      • Memory: Provide memory that will be used by our lambda function.

      • Timeout: Select a time for execution of lambda function for each request.

  4. Once you are done with all inputs, click “Next” which will show you to review the configuration.

  5. Once a review is completed, click on “Create Function”.

6. Invoke the Function

Once the AWS lambda function is created, we’ll test it by passing in some data:

  • Click on your lambda function from lists and then click on “Test” button

  • A popup window will appear which contains dummy value for sending data. Override the data with “Baeldung”

  • Click on “Save and test” button

On the screen, you can see the Execution result section with successfully returned output as:

"Hello World - Baeldung"

7. Conclusion

In this quick intro article, we’ve created a simple AWS Lambda app using Java 8, deployed that to AWS and tested it.

The full source code for the example app can be found over on Github.

Leave a Reply

Your email address will not be published.