DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Deploying Java Serverless Functions as AWS Lambda
  • Getting started with Java Serverless Functions using Quarkus and AWS Lambda
  • Building Scalable Data Lake Using AWS
  • Building a Scalable ML Pipeline and API in AWS

Trending

  • Event-Driven Microservices: How Kafka and RabbitMQ Power Scalable Systems
  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  • Code Reviews: Building an AI-Powered GitHub Integration
  • Apple and Anthropic Partner on AI-Powered Vibe-Coding Tool – Public Release TBD
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Write Your First AWS Lambda in Java

Write Your First AWS Lambda in Java

Learn how to create your first Lambda handler in Java using AWS SDK

By 
Rajan Panchal user avatar
Rajan Panchal
·
Sep. 21, 20 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
7.3K Views

Join the DZone community and get the full member experience.

Join For Free

So far, I have been writing Lambda function in Python for all my AWS projects. In Python its easy, just import boto3 module and starting coding. Things are bit different when you write Lambda handlers in Java. Lets explore and see how you can write a simple HelloWorld Lambda handler in java. I have planned couple of how-to projects that I am going to write in Java. Hence I thought to do HelloWorld post before we dive into complex handlers. Feel free to follow me on twitter for upcoming updates.

To implement handler, we are going to use Maven, Eclipse and AWS SDK for Java. Below are the version:

  • Java:  1.8.
  • Eclipse: Version: 2020-06 (4.16.0).
  • AWS SDK: 2.14.11.
  • Maven: 3.6.3 (Included with eclipse).

To get started, create a new empty maven project in eclipse. Go to File-> New-> Maven Project. In the new project dialog box, select "create simple project" and hit next. On next screen. add appropriate information about the project and hit finish. For example:

New Maven project

Now your project is created. Open pom.xml and add following code.

XML
xxxxxxxxxx
1
64
 
1
<project xmlns="http://maven.apache.org/POM/4.0.0"
2
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4
    <modelVersion>4.0.0</modelVersion>
5
    <groupId>net.rajanpanchal</groupId>
6
    <artifactId>lambda-java-demo</artifactId>
7
    <version>1</version>
8
    <name>Lambda-Java-Demo</name>
9
    <description>HelloWorld Lambda handler in java</description>
10
    <properties>
11
        <maven.compiler.source>1.8</maven.compiler.source>
12
        <maven.compiler.target>1.8</maven.compiler.target>
13
        <aws.java.sdk.version>2.14.11</aws.java.sdk.version>
14
    </properties>
15
    <dependencyManagement>
16
        <dependencies>
17
            <dependency>
18
                <groupId>software.amazon.awssdk</groupId>
19
                <artifactId>bom</artifactId>
20
                <version>${aws.java.sdk.version}</version>
21
                <type>pom</type>
22
                <scope>import</scope>
23
            </dependency>
24
        </dependencies>
25
    </dependencyManagement>
26
    <dependencies>
27
        <dependency>
28
            <groupId>com.amazonaws</groupId>
29
            <artifactId>aws-lambda-java-core</artifactId>
30
            <version>1.2.0</version>
31
        </dependency>
32
33
        <dependency>
34
            <groupId>com.google.code.gson</groupId>
35
            <artifactId>gson</artifactId>
36
            <version>2.8.6</version>
37
        </dependency>
38
    </dependencies>
39
    <build>
40
        <plugins>
41
            <plugin>
42
                <groupId>org.apache.maven.plugins</groupId>
43
                <artifactId>maven-compiler-plugin</artifactId>
44
                <configuration>
45
                    <source>${maven.compiler.source}</source>
46
                    <target>${maven.compiler.target}</target>
47
                </configuration>
48
            </plugin>
49
            <plugin>
50
                <groupId>org.apache.maven.plugins</groupId>
51
                <artifactId>maven-shade-plugin</artifactId>
52
                <version>3.2.4</version>
53
                <executions>
54
                    <execution>
55
                        <phase>package</phase>
56
                        <goals>
57
                            <goal>shade</goal>
58
                        </goals>
59
                    </execution>
60
                </executions>
61
            </plugin>
62
        </plugins>
63
    </build>
64
</project>


We are setting some properties in <properties> tag like AWS SDK version and Java Version. We are adding AWS SDK dependency and Lambda core dependency with desired version. The Google JSON dependency is added to convert between JSON and Java object and vice versa. In plugins, we define maven compiler plugin to compile the code and another important plugin called maven-shade-plugin. This plugin helps to create fat jar a.k.a Uber jar. This jar will contain all the dependencies that are required to successfully run the lambda function.

Now let's create the handler.

Java
xxxxxxxxxx
1
26
 
1
package net.rajanpanchal.handlers;
2
3
import java.util.Map;
4
5
import com.amazonaws.services.lambda.runtime.Context;
6
import com.amazonaws.services.lambda.runtime.LambdaLogger;
7
import com.amazonaws.services.lambda.runtime.RequestHandler;
8
import com.google.gson.Gson;
9
import com.google.gson.GsonBuilder;
10
11
public class HelloWorldHandler implements RequestHandler<Map<String,String>, String>{
12
      Gson gson = new GsonBuilder().setPrettyPrinting().create();
13
      @Override
14
      public String handleRequest(Map<String,String> event, Context context)
15
      {
16
        LambdaLogger logger = context.getLogger();
17
        String response = new String("200 OK");
18
        // log execution details
19
        logger.log("ENVIRONMENT VARIABLES: " + gson.toJson(System.getenv()));
20
        logger.log("CONTEXT: " + gson.toJson(context));
21
        // process event
22
        logger.log("EVENT: " + gson.toJson(event));
23
        logger.log("EVENT TYPE: " + event.getClass().toString());
24
        return response;
25
      }
26
    }


Here we are implementing RequestHandler that will accept a Map of String and outputs a String response. The handler is not doing much. Just logging some stuff from context and event  and in response it sends 200 OK string. After this, right click on project, go to 'Run as' and click 'Maven build'. A configuration window will open. In 'Goals' type package and hit 'Run' . Build should be successful and will create a fat jar in target folder.

Now, go to the AWS console and create a new Lambda function with Java 8 as runtime and upload this jar from Function Code section. In Basic Settings, you have to specify package.class::methodName in the handler text box. To test this Lambda, create a test event and execute the test.  

hello world in Java

The output might look similar to this:

Plain Text
xxxxxxxxxx
1
 
1
START RequestId: c40b4095-27f5-4153-ac37-fd2c103f4476 Version: $LATEST ENVIRONMENT VARIABLES: {   "PATH": "/usr/local/bin:/usr/bin/:/bin:/opt/bin",   "_AWS_XRAY_DAEMON_ADDRESS": "169.254.79.2",   "LAMBDA_TASK_ROOT": "/var/task",   "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "128",   "TZ": ":UTC",   "AWS_SECRET_ACCESS_KEY": "<keyid>",   "AWS_EXECUTION_ENV": "AWS_Lambda_java8",   "AWS_DEFAULT_REGION": "us-east-1",   "AWS_LAMBDA_LOG_GROUP_NAME": "/aws/lambda/helloworldjava",   "_HANDLER": "net.rajanpanchal.handlers.HelloWorldHandler::handleRequest",   "LANG": "en_US.UTF-8",   "LAMBDA_RUNTIME_DIR": "/var/runtime",   "AWS_SESSION_TOKEN": "<session token>",   "LD_LIBRARY_PATH": "/lib64:/usr/lib64:/var/runtime:/var/runtime/lib:/var/task:/var/task/lib:/opt/lib",   "_X_AMZN_TRACE_ID": "Root\u003d1-5f545c5d-22c8a803badd636859a0f387;Parent\u003d23df427f78bc46e4;Sampled\u003d0",   "AWS_SECRET_KEY": "<secret key>",   "AWS_REGION": "us-east-1",   "AWS_LAMBDA_LOG_STREAM_NAME": "2020/09/06/[$LATEST]57c598b33b164acf8e8151660249e50e",   "AWS_XRAY_DAEMON_ADDRESS": "169.254.79.2:2000",   "_AWS_XRAY_DAEMON_PORT": "2000",   "AWS_XRAY_CONTEXT_MISSING": "LOG_ERROR",   "AWS_LAMBDA_FUNCTION_VERSION": "$LATEST",   "AWS_ACCESS_KEY": "<access key>",   "AWS_LAMBDA_FUNCTION_NAME": "helloworldjava" }CONTEXT: {   "memoryLimit": 128,   "awsRequestId": "c40b4095-27f5-4153-ac37-fd2c103f4476",   "logGroupName": "/aws/lambda/helloworldjava",   "logStreamName": "2020/09/06/[$LATEST]57c598b33b164acf8e8151660249e50e",   "functionName": "helloworldjava",   "functionVersion": "$LATEST",   "invokedFunctionArn": "arn:aws:lambda:us-east-1:<AccountId>:function:helloworldjava",   "cognitoIdentity": {     "identityId": "",     "poolId": ""   },   "logger": {} }EVENT: {   "key1": "value1",   "key2": "value2",   "key3": "value3" }EVENT TYPE: class java.util.LinkedHashMapEND RequestId: c40b4095-27f5-4153-ac37-fd2c103f4476 REPORT RequestId: c40b4095-27f5-4153-ac37-fd2c103f4476    Duration: 516.04 ms    Billed Duration: 600 ms    Memory Size: 128 MB    Max Memory Used: 79 MB    Init Duration: 393.54 ms


Here we complete our first Lambda handler in Java. In next post we will see how we can implement API using AWS SDK.

AWS Java (programming language) AWS Lambda

Published at DZone with permission of Rajan Panchal. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Deploying Java Serverless Functions as AWS Lambda
  • Getting started with Java Serverless Functions using Quarkus and AWS Lambda
  • Building Scalable Data Lake Using AWS
  • Building a Scalable ML Pipeline and API in AWS

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!