AWS Lambda with Java-A Step By Step Tutorial

aws lambda using java
Sharing is Caring:

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 request to an API gateway endpoint or an object upload to S3 bucket.

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

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

What this Tutorial is all About?

In this tutorial you will learn to create and run a lambda function using java. Basically, you will create a simple maven project in eclipse ,add lambda support in 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 simple maven project and extending it to enable lambda support etc.

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

Prerequisite:

  • An AWS Account
  • Eclipse or your favorite IDE
  • Basic Java knowledge
  • Your 15 minutes of time

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

Steps required for this tutorial:

  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 will build this gradually starting from a very basis 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 favorite 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 like below and click finish.

aws lambda using java

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

Step 2: Add Lambda dependency

You need to add 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 maven shade plugin to build your code and prepare the standalone jar file. Simply add 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 step 1, 2 and 3 our complete pom.xml looks something like 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 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 case of our normal java program, execution starts from main() method. Similarly in case of lambda it starts with handler method.

There are ways to create lambda handler such as

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

Here we will use 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 above code in the class and save file.

Just to give you a little bit of background about handler method , the handleRequest() method has two parameters here. first is input which is input event provided to the lambda function and second is 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 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 new maven build and provide your goal as clean package as below screenshot.

aws lambda java build

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

If you have followed along and your artifact-Id was same as 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 login to AWS and proceed with 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 lambda console. This is how it looks like

AWS Lambda using Java Console

Click on Create function

There are three different option displayed here. However we will choose author from scratch option as you can see in 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 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 up in configuration tab.

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 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 function code section and click on actions drop down. It shows two options as below. Click on upload a .zip or .jar file

AWS Lambda using java

The dialog 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

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

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

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

Event configuration window opens with 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 total 9 step for this 😛 , I am already so excited to click the test button. 😀 😀

Let’s click on test and you can see 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 console as well “Input : Welcome to CloudKatha !!!”. Lambda prints all the log in cloudwatch 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 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.

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:

Sharing is Caring:

Leave a Reply

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