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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Java on AWS Using Lambda

Java on AWS Using Lambda

A practical guide to deploying Java Lambdas in AWS

Emmanouil Gkatziouras user avatar by
Emmanouil Gkatziouras
CORE ·
Oct. 11, 16 · Tutorial
Like (12)
Save
Tweet
Share
8.25K Views

Join the DZone community and get the full member experience.

Join For Free

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 an 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"
                }
            }
        }
    }
}

The 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.

AWS Amazon Web Services AWS Lambda Java (programming language)

Published at DZone with permission of Emmanouil Gkatziouras, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • A Beginner's Guide to Back-End Development
  • Integration: Data, Security, Challenges, and Best Solutions
  • Core Machine Learning Metrics
  • How To Convert HTML to PNG in Java

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: