How to create AWS Lambda Function using Java

Rahul Chauhan
4 min readDec 12, 2020

--

AWS Lambda Introduction

AWS Lambda is a serverless compute service that lets you run code without provisioning or managing servers, creating workload-aware cluster scaling logic, maintaining event integrations, or managing runtimes. With Lambda, you can run code for virtually any type of application or backend service — all with zero administration.

Prerequisites

  1. An AWS Account
  2. An IDE — Eclipse or Intellij (We will use Intellij for this tutorial)
  3. Maven — To create a jar file which we will later use to upload it to the function code.

In this tutorial, we will create a function that will calculate the age of the person by passing the date of birth as an input.

Lets Start

  1. Create an AWS account

2. Go to AWS Management Console and search for Lambda and click on it.

3. Now click on the Create Function button

Now we have to add some basic information for our function.

  1. Let’s name our lambda function as calculateAge.
  2. Set runtime to Java 8

After adding basic information, click on Create Function.

Let’s write our core lambda function logic.

  1. Open Intellij
  2. Create New Project and select Maven (as shown below)

3. Click on Next and set a project name

4. Click on finish

5. Open your pom.xml file and add the following code

6. Create new package com.aws under src -> main -> java then create a new Java class as AwsLambdaRequest.java

7. Now create another class as AwsLambdaApp.java, which will have our core logic to calculate age.

8. Open cmd and navigate to your maven project directory (having pom.xml file)

9. Now run mvn package command. This command will create .jar package for our maven project which we will use to upload to function code

NOTE: The highlighted text is the path to the jar file. In my case, the path is C:\dev_space\AWS Lambda Demo\target\AWSLambdaDemo-1.0-SNAPSHOT-shaded.jar

10. Now open your lambda function that you have created in the Amazon console and go to Function Code section. Click on Actions and select Upload a .zip or .jar file and then click on Deploy.

11. Go to Runtime settings section and click on Edit. Update the handler info as shown below

Runtime should be set as Java 8. And com.aws is the Package name that contains the AwsLambdaApp.java file and handleRequest is the method which will be called. Then click on Save.

Now we have successfully created our lambda function and also deployed it to the server. We will now test it

12. Now click on the Test button and Configure test event. Leave Event template as it is and Enter name as calculateAge.

Update the JSON as follows

{
“day”: “05”,
“month”: “11”,
“year”: “1992”
}

and click on the Create button.

Now click on the Test button and under Execution result section, you will see the age as shown bellow

That’s it. I hope that you find this tutorial helpful and knowledgeable :) .

--

--

No responses yet