AWS Lambda is a serverless compute service offered by Amazon Web Services (AWS). It enables developers to run code without provisioning or managing servers.
Lambda executes code in response to events and automatically manages the computing resources required by that code. This eliminates the need to worry about server maintenance, scaling, and capacity provisioning.
In this tutorial, we will guide you through building your first AWS Lambda function using Core Java and deploying it to AWS Lambda.
The complete code for this project is available on my GitHub repository (getButton) #text=(GitHub) #icon=(share) #color=(#000000)
Project Dependencies
aws-lambda-java-core
is the essential dependency for executing your first AWS Lambda function using Core Java. While this is mandatory, you may also utilize optional dependencies when integrating with other AWS services.
Maven
<dependencies>
<!-- Defines handler method interfaces and the context object that the runtime passes to the handler.
If you define your own input types, this is the only library that you need. -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.2.3</version>
</dependency>
<!-- Optional - Input types for events from aws services that invoke Lambda functions. -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
<version>3.14.0</version>
</dependency>
</dependencies>
Create a deployable JAR file for AWS Lambda using the Maven Shade Plugin, including all necessary built-in libraries.
<!-- building bundle jar to deploy in aws lambda -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
Gradle
dependencies {
// Defines handler method interfaces and the context object that the runtime passes to the handler.
// If you define your own input types, this is the only library that you need.
implementation 'com.amazonaws:aws-lambda-java-core:1.2.3'
// Optional - Input types for events from aws services that invoke Lambda functions.
implementation 'com.amazonaws:aws-lambda-java-events:3.14.0'
}
// building bundle jar to deploy in aws lambda
jar {
from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
}
Designing Request and Response Objects for AWS Lambda Handlers
This tutorial requires Java 17 or later. From Java 17 onwards, you can effectively create Java classes or records to elegantly handle request payloads (Lambda events) and responses
For simplicity, I will create two Java records: one for the request and another for the response, each containing relevant parameters.
Request Payload (Lambda Event)
package in.learnjavaskills;
public record Request(Integer id, String message) {}
Response
package in.learnjavaskills;
public record Response(Integer statusCode, String message) {}
Configuring Lambda Handlers in Java
Let's begin by creating a Java class that implements the RequestHandler
interface and overrides the handleRequest()
abstract method.
The AWS Lambda function limits us to completing the execution of the entire function within 15 minutes, which implies we can only perform a function execution within 15 minutes.(alert-warning)
package in.learnjavaskills;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class LambdaHandler implements RequestHandler<Request, Response> {
/**
* Accept a Request object containing two parameters: an integer 'id' and a string 'message'.
* Log the received request and then return a 200 status response with a success message.
*/
@Override
public Response handleRequest(Request request, Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Lambda handler request function invoked with request : " + request.toString());
return new Response(200, "Success");
}
}
• handleRequest()
is the main method where your Lambda function's logic resides.
• Context
provides information about the invocation, function, and execution environment(e.g., remaining time, log stream name, etc.).
• The RequestHandler<I, O>
interface is the cornerstone of developing AWS Lambda functions in Java.
It serves as a contract for your Lambda function's execution logic. By implementing this interface, you tell the Lambda runtime how to handle incoming requests and generate responses.
<I, O>
: These represent the input (request) and output (response) types of your Lambda function. You define these based on the specific data your function expects and produces.(alert-passed)
Creating and Deploying Lambda Functions with the AWS Management Console
Navigate to the AWS Management Console at (getButton) #text=(Amazon Console) #icon=(link) #color=(#d35400) Sign in with your AWS credentials if you haven't already. Search for 'Lambda' and click on 'Create function'.
Select the 'Author from scratch' option, provide an appropriate name for your AWS Lambda function (e.g., 'core-java-aws-lambda-function'), and then click the 'Create function' button.
Upon successful creation of your Lambda function, you will see the following success message.
Upload your bundled JAR file. Scroll down to the 'Code' section and select 'Upload from' dropdown button. Then, choose '.zip or .jar file' since you have your bundled JAR.
The AWS Lambda function allows us to upload a jar with a maximum size of 50 MB, and if the jar size is larger than or equivalent to 10 MB, we should use AWS S3.(alert-success)
An upload window will appear. Click the 'Upload' button (as shown in the screenshot below) and select your bundled JAR file from your local machine. Finally, click the 'Save' button.
Next, let's configure the Runtime Settings. Here, you can update the Java version and specify the request handler method path. Click the 'Edit' button to proceed.
In the 'Handler' field, specify in.learnjavaskills.LambdaHandler::handleRequest
. You must update this value to match your package, class name, and method name (e.g., your.package.ClassName::yourMethod
). You can also configure the Java runtime version, which is set to Java 21 in this example.
Finally, test your Lambda function. Navigate to the Test
section and create a new test event. Give it a name (e.g., "test-function") and provide the Event JSON.
This JSON represents the request payload for your function. In our example, we created a Request
Java record with an integer 'id' and a string 'message'.
Therefore, the Event JSON should include these two parameters, which your Lambda function expects to receive."
Upon clicking the 'Test' button, you will receive the response from your Lambda function. In this case, you should see a 200 status code and a 'success' message.
Once you've finished your lab exercise, remember to delete your AWS lambda function, layer, and API Gateway.(alert-error)
Conclussion
This tutorial demonstrates how to develop AWS Lambda functions using Core Java and deploy them to the AWS Lambda service. To minimize dependencies, leverage the Lambda Layer functionality to deploy a command library.
AWS Lambda functions have a 15-minute maximum execution time limit.
While direct CPU size configuration is not possible, increasing the allocated memory will proportionally increase the available CPU power
Learn how to build serverless functions with (getButton) #text=(Spring Cloud Function) #icon=(link) #color=(#35a576), seamlessly deploy them on AWS Lambda, and create RESTful APIs using AWS API Gateway in this comprehensive blog.
The complete code for this project is available on my GitHub repository (getButton) #text=(GitHub) #icon=(share) #color=(#000000)
Keep learning and keep growing.