Loading...

Sharing what we learn—it’s our way of giving back.

Developing and managing custom applications, we encounter a variety of needs,
challenges, and perspectives. It’s our hope you find these articles helpful in
guiding your own work and avoiding a few pitfalls along the way.

AWS Lambda

AWS Lambda

AWS Lambda is a serverless computing service which can be triggered based on events. It executes code based on the received event and provides a response accordingly. Lambda can be scaled as needed without any human intervention.

Like most AWS services, pricing for Lambda is pay-as-you-go. Specifically, it's based on the amount of memory used and request processing time.

Of note, AWS Lambda supports multiple languages which can be configured when a function is created.

The following languages are supported by Lambda:

  • C#
  • Java 8
  • Node.js 4.3
  • Node.js 6.10
  • Python 2.7
  • Python 3.6

In this article, we step through an example using Java 8.

Create Application Handler

1.) First, add the Lambda dependency to your pom.xml file.

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

This dependency provides Lambda handler interfaces which can be used for creating handler classes. Also, it provides classes like Context which can be used for getting Lambda execution environment information.

2.) We need to create an entry point handler class which will have the method called when our Lambda function is invoked. We can create a handler class in 3 ways:

a. Custom Handler
Using a custom handler, we create a class and method which will be the entry point for our request.

public class GreetingsHandler {
    public String processRequest(String input, Context context) {
        context.getLogger().log(input);
        return "Welcome " + input + " to AWS Lambda";
    }
}

 “processRequest” will be the entry point method for the Lambda event. Here, we are accepting the input of type String and Context to get the information about the Lambda execution environment at runtime.

b. Using RequestHandler Interface
Using a RequestHandler interface, we define what will be our input and output type. Input and Output serialization will be handled by the Lambda environment.

public class GreetingsRequestHandler  implements RequestHandler<String, String> {
    @Override
    public String handleRequest(String input, Context context) {
        context.getLogger().log(input);
        return "Welcome " + input + " to AWS Lambda";
    }
}

Here we take input as String and output as String.

c. Using RequestStreamHandler Interface
Using a RequestStreamHandler interface, we can read and write byte data using streams. This is useful when you don’t want to use Lambda’s serializations approach or Lambda’s serialization doesn’t fit your requirements.

public class GreetingsRequestStreamHandler implements RequestStreamHandler {
    @Override
    public void handleRequest(InputStream inputStream,
                              OutputStream outputStream,
                              Context context) throws IOException {
        String input = new BufferedReader(new InputStreamReader(inputStream))
                .lines()
                .parallel()
                .collect(Collectors.joining("\n"));
        context.getLogger().log(input);
        outputStream.write(("Welcome " + input + " to AWS Lambda").getBytes());
    }
}

Here, we are reading the byte data and converting to String from InputStream and writing the byte data to OutputStream.

Create Deployment Package

3. An AWS Lambda function accepts either a .zip file or .jar file for Java 8 runtime language. We can use a variety of build and packaging tools to create either of the files. For our example, we will use the Maven plugin. Let’s see how to create a deployment package.

a. Creating .jar File
We need to use the Maven Shade plugin which will add our compiled code, extract dependencies included in pom.xml, and create a standalone .jar file. We have two options to add the Maven Shade plugin - either use Maven goal “mvn clean package shade:shade” in maven command while building the project or add the following plugin to your pom.xml:

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

b. Creating .zip File
To create a .zip file, we need to use the Maven assembly plugin. The .zip file should contain files in the following structure:

  • Our compiled classes and resources at root level
  • All dependencies in “lib” folder

Add the following plugin in pom.xml

<plugin>    
  <groupId>org.apache.maven.plugins</groupId>    
  <artifactId>maven-assembly-plugin</artifactId>    
  <version>3.1.0</version>    
  <configuration>       
    <descriptors>          
      <descriptor>assembly.xml</descriptor>       
    </descriptors>    
  </configuration>    
  <executions>       
    <execution>          
      <id>assembly</id>          
      <phase>package</phase>          
      <goals>             
        <goal>single</goal>          
      </goals>       
   </execution>    
  </executions> 
</plugin>

Create a new file “assembly.xml” at the same level of pom.xml.

<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
	<id>assembled</id>
	<formats>
		<format>zip</format>
	</formats>
	<includeBaseDirectory>false</includeBaseDirectory>
	<fileSets>
		<fileSet>
			<directory>${project.build.directory}/classes</directory>
			<outputDirectory>/</outputDirectory>
			<includes>
				<include>**/*.class</include>
			</includes>
		</fileSet>
		<!-- Include fileSet for any resource files you want to add in .zip file -->
	</fileSets>
	<dependencySets>
		<dependencySet>
			<outputDirectory>lib</outputDirectory>
			<useProjectArtifact>false</useProjectArtifact>
		</dependencySet>
	</dependencySets>
</assembly>

In the target folder, you can check the .zip file.

Create and Configure Lambda Function

1.) Sign-in to the AWS Console (https://aws.amazon.com/)

2.) Click on “Lambda” under “Compute” or go to https://console.aws.amazon.com/lambda/home

3.) Click “Create a Function

Here, you can see multiple preconfigured Lambda functions exist. You can either choose one of the existing ones or create a new one from scratch.

.Create Function

Click “Author from scratch

4.) Configure Triggers

Here, we can create triggers on AWS Lambda which can be invoked on events occurring on other AWS services like S3, SNS, SQS, Kinesis, etc. For our example, we will not configure any triggers.

Click “Next

5.) Configure Function

First, provide the Basic information:

Then provide function code (.zip or .jar file) – here choose “Upload a .ZIP or .JAR file” option, and upload the deployment package file.

Then, provide details for the function handler and role to grant access to AWS services using this Lambda function. The handler names should be in the following format:

For GreetingsHandler:

com.addo.lambda.GreetingsHandler::processRequest

For GreetingsRequestHandler:

com.addo.lambda.GreetingsRequestHandler::handleRequest

For GreetingsRequestStreamHandler:

com.addo.lambda.GreetingsRequestStreamHandler::handleRequest


And for role, choose “Create a custom role” and it will redirect to the appropriate screen. On the create role screen, keep the default grants and click on “Allow


This will create the role and will be selected under the “Existing role”.


Next, configure “Tags” and “Advanced settings”. For our example, we will use the default values.

Click “Next

6.) Review the configuration, and click “Create function”

Test Lambda Function

1.) To test a Lambda function independently, go to the AWS Management Console and then Lambda services. Go to the specific Lambda function and click “Test.”
2.) Configure Test Data

Click “Save and test

3.) Test executed successfully

You can see the response “Welcome Addo to AWS Lambda” which is returned from our Lambda function.

Conclusion

In this article, we have seen how to create Lambda function code using Java 8, create a deployment package, and configure a Lambda function using the AWS Management Console.

Contact Us

Have a question about us or our service? Feel free to
send us a note anytime, or call us during business
hours, Monday - Friday, 9am to 5pm EST.

133 W. Market St, #279
Indianapolis, IN 46204

(877) 630-2336