DEV Community

amarpreetbhatia
amarpreetbhatia

Posted on

Getting Started with the AWS SDK for Java and Lambda

Are you a Java developer looking to use AWS Lambda in your projects? While JavaScript is the most common language used for writing Lambda functions, it is also possible to use Java to create and invoke these serverless functions. In this article, I will provide a step-by-step guide for setting up Java and Maven to use the AWS SDK for Lambda. By the end of this tutorial, you will have a solid understanding of how to use Java to work with AWS Lambda and incorporate serverless computing into your Java-based projects.

To set up Java and Maven to use the AWS SDK for Lambda, you will need to:

  • Install the Java Development Kit (JDK) if you do not already have it installed. You can download the JDK from the Oracle website: JAVA SDK Try to use LTS version i.e. JDK 17 in latest, but ideally any JAVA SDK after 1.8+ is ok to run this sample.
  • Install Maven if you do not already have it installed. You can find instructions for installing Maven on the Apache Maven website: Maven
  • Once you have installed JDK and Maven, create a new Maven project in your preferred development environment. Add the AWS SDK for Java as a dependency in your Maven project by including the following code in your pom.xml file:
<dependencies>
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk</artifactId>
        <version>1.11.871</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Here is an example of a simple Java program that you can run on AWS Lambda

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

public class HelloWorld implements RequestHandler<Object, String> {
    public String handleRequest(Object input, Context context) {
        return "Hello, World!";
    }
}
Enter fullscreen mode Exit fullscreen mode

This program implements the RequestHandler interface, which is the main interface that you need to implement to create a function that can be invoked by AWS Lambda. The handleRequest method is the function handler, which takes an input object and a context object as arguments and returns a string.

To run this program on AWS Lambda, you would need to package it into a .zip file along with any dependencies and upload it to AWS Lambda using the steps described in my previous message. The fully qualified name of the class containing the function handler method would be HelloWorld.

To set up a Java program for AWS Lambda, follow these steps:

  • Create a new AWS Lambda function in the AWS Management Console.
  • Choose "Java" as the runtime for your function.
  • Under "Function code," choose "Upload a .zip file" as the code entry type and upload your .zip file containing your Java code and any dependencies.
  • In the "Handler" field, specify the fully qualified name of the class that contains the function handler method. The function handler is the method that will be invoked when your Lambda function is called.
  • Configure the function's execution role and any other desired settings, such as the function's memory and timeout settings.
  • Save your function and test it using the "Test" button in the AWS Management Console. That's it! Your Java program should now be set up and ready to run on AWS Lambda. You can invoke your function using the AWS Management Console, the AWS CLI, or by making an API call.

Now, Here is a sample Java program that demonstrates to invoke an AWS Lambda function:
But, first we need to get an access Token, To set the access token in your Java code when invoking an AWS Lambda function, you will need to do the following:

  • Obtain an access token from AWS Identity and Access Management (IAM). You can use the GetAccessToken API to request an access token for a specific IAM user or role.
  • Set the access token in your Java code by including it in the InvokeRequest object that you use to invoke your Lambda function. You can set the access token by calling the withAccessToken method of the InvokeRequest object and passing in the access token as a string.
import com.amazonaws.services.lambda.AWSLambda;
import com.amazonaws.services.lambda.AWSLambdaClientBuilder;
import com.amazonaws.services.lambda.model.InvokeRequest;
import com.amazonaws.services.lambda.model.InvokeResult;

public class LambdaInvoker {
    public static void main(String[] args) {
        // Create a client for interacting with AWS Lambda
        AWSLambda lambdaClient = AWSLambdaClientBuilder.defaultClient();

        // Set the name of the Lambda function to invoke
        String functionName = "myFunction";

        // Set the input for the Lambda function
        String input = "{\"key\":\"value\"}";

        // Set the access token for the InvokeRequest
        String accessToken = "ACCESS_TOKEN_HERE";

        // Create an InvokeRequest object
        InvokeRequest invokeRequest = new InvokeRequest()
                .withFunctionName(functionName)
                .withPayload(input)
                .withAccessToken(accessToken);

        // Invoke the Lambda function and get the response
        InvokeResult invokeResult = lambdaClient.invoke(invokeRequest);

        // Print the response
        System.out.println(new String(invokeResult.getPayload().array()));
    }
}
Enter fullscreen mode Exit fullscreen mode

This program will invoke the AWS Lambda function named myFunction, passing it the JSON input {"key":"value"}. It will then print the response returned by the function.

In the End one can say, why not to use AWS API Gateway for Integrating to call the Lambda function, which is very valid and depends on the use case of the project you are working on.

There are broadly three invocation models and the example above comes under "Synchronous invocation", other two are Asynchronous invocation and Polling invocation. More details can be read from Lambda invocation

I hope this helps! If you have any thoughts or questions about using Java with AWS Services, please don't hesitate to reach out in the comments below. I would love to hear from like minded people and gain more knowledge.

Top comments (0)