Skip to main content

Deploy Java SDK in AWS Lambda

Last updated on

Overview

This page provides information on how to deploy Java SDK code in AWS Lambda services.

Before you begin

  • Use similar Java SDK code as in the Java SDK example.
  • AWS Lambda supports Java 8 runtime only, so ensure you use JDK 1.8.

Step-by-step Guide

  1. Add AWS Lambda dependency

    In the pom.xml file of the downloaded project, add the following inside the <dependencies> block:

    <dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-lambda-java-core</artifactId>
    <version>1.0.0</version>
    </dependency>
  2. Update your Java class

    • Open SplitSDK_Sample.java

    • Add these imports at the top:

      import com.amazonaws.services.lambda.runtime.Context;
      import com.amazonaws.services.lambda.runtime.RequestHandler;
    • Modify the class declaration:

      public class SplitSDK_Sample implements RequestHandler<Object, String> {
  3. Move your main method code into handleRequest

    Replace the main method code with the following handleRequest method:

    @Override
    public String handleRequest(Object input, Context context) {
    String myinput = input.toString();
    System.out.print("Input: " + myinput + "\n\n");
    HashMap<String, String> mapInput = (HashMap<String, String>) input;
    String userId = mapInput.get("key1");
    String treatment = "";
    try {
    MySplit split = new MySplit("API KEY");
    treatment = split.GetSplitTreatment(userId, "Split Name");
    System.out.print("Treatment: " + treatment + "\n\n");
    split.Destroy();
    } catch (Exception e) {
    System.out.print("Exception: " + e.getMessage());
    }
    return treatment;
    }
  4. Build your project

    • In Eclipse, select ProjectBuild Project, and ensure no build errors.

    • Right-click your project in Project Explorer → Export.

    • Choose Runnable JAR fileNext.

    • Specify JAR location and name.

    • Select Extract required libraries into generated JARFinish.

  5. Deploy to AWS Lambda

    • Login to AWS Console

    • Go to LambdaFunctions

    • Click Create function

    • Choose Author from scratch

    • Select Java 8 runtime

    • Give your function a name

    • Click Create function

    • Under Function code, upload your generated JAR file and save.

  6. Configure test event

    • In the Lambda console, select Configure test events
    • Use the Hello World template
    • Set a value for key1 that matches the user ID your Lambda function will use.
    • Name and create the event

  7. Set Lambda handler

    • In the Function code section, set the handler to:

      sample.SplitSDK_Sample::handleRequest

    • Click Save.

  8. Test your Lambda function

    • Click Test.
    • You should see the expected treatment value as output.
    • Logs will show debug information.

Download the example project.