AWS Lambda with Java-A Step By Step Tutorial

aws lambda using java

AWS Lambda with Java-A Step By Step Tutorial

AWS Lambda is the serverless computing platform offered by AWS. It lets you run code without creating or managing any servers. Your code runs in response to events such as requests to an API gateway endpoint or an object upload to an S3 bucket.

The good thing about lambda is that you pay only when your code is running and not for idle time. That means it’s very cost-effective.

If you are new to lambda, I highly recommend having a look at the official documentation.

Don’t want to miss any posts from us? join us on our Facebook group, and follow us on Facebook, Twitter, LinkedIn, and Instagram. You can also subscribe to our newsletter below to not miss any updates from us.

What this Tutorial is all About?

In this tutorial, you will learn to create and run an AWS lambda function using Java. Basically, you will create a simple maven project in Eclipse, add lambda support to the project, create packaged jar and deploy the jar into AWS Lambda.

Although there are many ways to create AWS lambda function using Java such as-

  1. Create a lambda project with AWS toolkit-enabled eclipse
  2. Using AWS CodeStar to get started with CICD-ready Java lambdas
  3. Creating a simple maven project and extending it to enable lambda support etc.

We’ll use the third option out of three because it will help us understand things from scratch.

Prerequisite:

After completing this tutorial you should be able to create, deploy, test and delete your lambda function.

Steps to Create AWS Lambda with Java

  1. Create a Java Project
  2. Add Lambda dependency
  3. Add Maven Shade Plugin
  4. Write Code for your Lambda
  5. Package your application in a jar
  6. Create Lambda function in AWS Lambda Console
  7. Upload you code to AWS Lambda
  8. Configure the Lambda function
  9. Configure Test Event
  10. Test Your Lambda
  11. Delete your lambda

Don’t worry much about all the steps. We’ll build this gradually starting from a very basic maven project.

Are you ready? Let’s go !!!

Step 1: Create a Java Project

First of all, we need to create a Java project. In order to do that, open your favourite IDE and create a Java project(maven).

If you are using Eclipse, Click on File->New-> Maven Project

Select the checkbox – Create a simple project(Skip archetype selection) and click next.

Fill up all the information below and click finish.

aws lambda using java

After clicking finish, in a few minutes, the project is created. Once the project is created you can go to step 2 to add lambda support to our project.

Step 2: Add Lambda dependency

You need to add the below dependency in your pom.xml to enable AWS Lambda support.

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

Step 3: Add Maven Shade Plugin

In addition to adding lambda support in your pom, you also need to add the maven shade plugin to build your code and prepare the standalone jar file. Simply add the Maven shade plugin as mentioned below.

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

After completing steps 1, 2 and 3, our complete pom.xml looks something like the below.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.cloudkatha.demo</groupId>
	<artifactId>lamda-demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Lambda-Demo</name>
	<description>First Java Lambda</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

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

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

</project>

Step 4: Write Code for your Lambda

Now when we have a project, lambda support in the project and a way to build the jar. We can start with writing code for lambda.

Every lambda function needs a handler. A handler is nothing but the entry point for lambda to start executing your code.

for example- in the case of our normal Java program, execution starts from the main() method. Similarly, in the case of lambda, it starts with the handler method.

There are ways to create lambda handlers such as

  • Creating Custom Lambda Handler
  • Implementing RequestHandler interface
  • Implementing RequestStreamHandler interface

Here we will use the simplest possible custom handler as mentioned in the code snippet below.

package com.cloudkatha.demo;

import com.amazonaws.services.lambda.runtime.Context;

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

Navigate to src/main/java folder, Right click -> New -> Class Create a new class LambdaHandler under the package com.cloudkatha.demo or whatever you want and put the above code in the class and save the file.

Just to give you a little bit of background about the handler method, the handleRequest() method has two parameters here. first is input which is the input event provided to the lambda function and second is the context which gives information about the invocation, function, and execution environment.

Step 5: Package your Application in a jar

Now when we are done creating the handler, We need to package our application and create a jar file which we will upload into AWS lambda.

Right-click on your project -> Run as -> Run Configurations -> Create a new maven build and provide your goal as clean package as in the below screenshot.

aws lambda java build

Click Run and check the console as the project is building. Once successful checkout the target folder.

If you have followed along and your artifact-Id was the same as the demo,you should be able to see two jar files in the target folder-

  • demo-0.0.1-SNAPSHOT.jar
  • original-demo-0.0.1-SNAPSHOT.jar

demo-0.0.1-SNAPSHOT.jar is what we need to upload to AWS lambda. Now we are ready with the packaged jar so it’s time to log in to AWS and proceed with the next step.

Step 6: Create Lambda function in AWS lambda console

Before we upload our code to AWS lambda, we will need to create a bare lambda function first. So let’s go ahead and do that.

Login to AWS Management Console. Search for lambda and click lambda to open the lambda console. This is how it looks like

AWS Lambda using Java Console

Click on Create function

There are three different options displayed here. However, we will choose the author from scratch option as you can see in the below screenshot.

AWS Lambda Creation Screen

Fill up basic information like function name and choose Java 8 in runtime as mentioned below.

aws lambda permission

In permission click on Choose or create an execution role. Here you can choose an existing role or create one from the policy. However, we will leave this as default to create a new role with basic lambda permissions.

Once everything is filled up click on create function.

After some time lambda function is created and we land in the configuration tab.

The first thing present here is Add Trigger. As you know that lambda runs in response to an event/trigger. But in this case, we will simply use a test event to test our lambda. So you can ignore it for the time being.

Step 7: Upload your Code to AWS Lambda

Scroll down to the function code section and click on the actions drop-down. It shows two options as below. Click on Upload a .zip or .jar file

AWS Lambda using java

The dialogue will open to upload your file. Upload the jar file prepared in step 5 here by navigating to your target folder and choosing demo-0.0.1-SNAPSHOT.jar

Click on save.

After the jar is uploaded you will see “Successfully updated the function First-Lambda”.

Step 8: Configure the Lambda function

We have uploaded our code to lambda. Now it’s time to tell lambda about our handler method. So in this step, we will configure the Lambda to use our handler method.

Scroll down to Basic Settings and click Edit.

Change the handler to com.cloudkatha.demo.LambdaHandler::HandleRequest as mentioned below and click on save.

aws lambda using java permission

The handler format is package.class::handleRequest in case you have a different class name and package name then you can configure the handler accordingly.

Please note that here you can change the memory allocated to the lambda function and timeout as well. However, we will keep this as default as of now for simplicity.

The Lambda function is updated again and now points to our handler.

Step 9: Configure Test Event

As I mentioned earlier lambda runs in response to the event. So our lambda is currently deployed but sitting idle and not doing anything.

Well, you can go ahead and create an actual trigger such as an API gateway endpoint or s3 bucket upload trigger. However, for simplicity, we will use a test event only.

Let’s configure a test event to invoke our lambda.

Click on Select a test event dropdown ->Click on Configure test events

The event configuration window opens with the hello-world default template. You can change that however it’s not required for this tutorial. Fill up details like event name and event body.

Please note that our lambda function is accepting string input so remove JSON body and provide simple string as mentioned in the screenshot and click create.

configure event

Step 10: Test your lambda

We have waited for a total of 9 steps for this :P, I am already so excited to click the test button. 😀 😀

Let’s click on test and you can see the Execution Result: succeeded and also the output as: “Hello World – Welcome to CloudKatha !!!”

Congratulations !!! You ran your first AWS lambda using java successfully 🙂

successful lambda execution

If you notice, the log that we had in our code is printed on the console as well “Input: Welcome to CloudKatha !!!”. Lambda prints all the log-in cloud watch and makes it easy for us to debug our application.

Step 11: Delete your lambda

Now we are done learning our first lambda using Java. So it’s time to delete it.

Click on Actions dropdown -> Click Delete function

Delete Lambda

Lambda is successfully deleted.

Conclusion

In this tutorial we –

  • Created a Java project
  • We added lambda dependency and maven shade plugin to the project
  • packaged our application into a standalone jar file and deployed it into AWS lambda.
  • Configured the test event and invoked our lambda successfully

That was all about this tutorial. If you get stuck at any point feel free to leave a comment and I will reply to you as soon as possible.

Enjoyed the content?

Subscribe to our newsletter below to get awesome AWS learning materials delivered straight to your inbox.

Liked reading my post? you can motivate me by-

  • Adding a comment below on what you liked and what can be improved.
  • Follow us on
  • Share this post with your friends and colleagues.

Also Read:

Leave a Reply

Your email address will not be published. Required fields are marked *