Enterprise Java

Java on the AWS cloud using Lambda

Amazon Web Services gets more popular by the day. Java is a first class citizen on AWS and it is pretty easy to get started.
Deploying your application is a bit different, but still easy and convenient.

AWS Lambda is a compute service where you can upload your code to AWS Lambda and the service can run the code on your behalf using AWS infrastructure. After you upload your code and create what we call a Lambda function, AWS Lambda takes care of provisioning and managing the servers that you use to run the code.

Actually think of lambda as running a task that needs up to five minutes to finish. In case of simple actions or jobs that are not time consuming, and don’t require a huge framework, AWS lambda is the way to go. Also AWS lambda is great for horizontal scaling.

The most stripped down example would be to create a lambda function that responds to a request.

We shall implement the RequestHandler interface.

package com.gkatzioura.deployment.lambda;

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

import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by gkatzioura on 9/10/2016.
 */
public class RequestFunctionHandler implements RequestHandler<Map<String,String>,String> {

    private static final Logger LOGGER = Logger.getLogger(RequestFunctionHandler.class.getName());

    public String handleRequest(Map <String,String> values, Context context) {

        LOGGER.info("Handling request");

        return "You invoked a lambda function";
    }

}

Somehow RequestHandler is like a controller.

To proceed we will have to create a jar file with the dependencies needed, therefore we will create a custom gradle task

apply plugin: 'java'

repositories {
    mavenCentral()
}

dependencies {
    compile (
            'com.amazonaws:aws-lambda-java-core:1.1.0',
            'com.amazonaws:aws-lambda-java-events:1.1.0'
    )
}

task buildZip(type: Zip) {
    from compileJava
    from processResources
    into('lib') {
        from configurations.runtime
    }
}

build.dependsOn buildZip

Then we should build

gradle build

Now we have to upload our code to our lambda function.

I have a s3 bucket on amazon for lambda functions only. Supposing that our bucket is called lambda-functions (I am pretty sure it is already reserved). We will use aws cli wherever possible.

aws s3 cp build/distributions/JavaLambdaDeployment.zip s3://lambda-functions/JavaLambdaDeployment.zip

Now instead of creating a lambda function the manual way we are going to do so by creating a cloud formation template.

{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Resources": {
    "LF9MBL": {
      "Type": "AWS::Lambda::Function",
      "Properties": {
        "Code": {
          "S3Bucket": "lambda-functions",
          "S3Key" : "JavaLambdaDeployment.zip",
        },
        "FunctionName": "SimpleRequest",
        "Handler": "com.gkatzioura.deployment.lambda.RequestFunctionHandler",
        "MemorySize": 128,
        "Role":"arn:aws:iam::274402012893:role/lambda_basic_execution",
        "Runtime":"java8"
      },
      "Metadata": {
        "AWS::CloudFormation::Designer": {
          "id": "66b2b325-f19a-4d7d-a7a9-943dd8cd4a5c"
        }
      }
    }
  }
}

Next step is to upload our cloudformation template to an s3 bucket. Personally I use a separate bucket for my templates. Supposing that our bucket is called cloudformation-templates

aws s3 cp cloudformationjavalambda.template s3://cloudformation-templates/cloudformationjavalambda.template

Next step is to create our cloudformation stack using the template specified

aws cloudformation create-stack --stack-name JavaLambdaStack --template-url https://s3.amazonaws.com/cloudformation-templates/cloudformationjavalambda.template

In order to check we shall invoke the lambda function through the amazon cli

aws lambda invoke --invocation-type RequestResponse --function-name SimpleRequest --region eu-west-1 --log-type Tail --payload '{}' outputfile.txt

And the result is the expected

"You invoked a lambda function"

You can find the source code on github.

Reference: Java on the AWS cloud using Lambda from our JCG partner Emmanouil Gkatziouras at the gkatzioura blog.

Emmanouil Gkatziouras

He is a versatile software engineer with experience in a wide variety of applications/services.He is enthusiastic about new projects, embracing new technologies, and getting to know people in the field of software.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button