
This guide will walk you through the best practices of using Java on AWS Lambda. To understand and implement these best practices, you will go over the history of Java, evolution of computing, and the challenges we face building serverless Java applications on AWS Lambda.
A simple Java Lambda function would look like the following:
package com.example;
public class HelloHandler {
public HelloResponse handleRequest(HelloRequest request) {
String message = "Hello " + request.getName();
HelloResponse response = new HelloResponse();
response.setMessage(message);
return response;
}
}
Advanced usage of a Lambda function would involve additional dependencies which you would normally use for production grade applications. Here are some of those core dependencies:
com.amazonaws:aws-lambda-java-core which provides the handler interfaces, and context object.com.amazonaws:aws-lambda-java-events which provides input types for events from AWS services.Here is an example using handler interface:
public class App implements RequestHandler<RequestEvent, ResponseEvent> {
public ResponseEvent handleRequest(RequestEvent event, Context context) {
// Process incoming event payload
return ResponseEvent().builder()
.withStatusCode(200)
.withBody("Hello World")
.build();
}
}
Here is an example
of using aws-lambda-java-events
library to serialize incoming events from Amazon API Gateway, Amazon SQS, and Amazon S3:
Amazon API Gateway
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
public class UnicornRequestHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
@Override
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) { }
}
Amazon SQS
import com.amazonaws.services.lambda.runtime.events.SQSEvent;
import com.amazonaws.services.lambda.runtime.events.SQSBatchResponse;
public class UnicornQueueProcessor implements RequestHandler<SQSEvent, SQSBatchResponse> {
@Override
public SQSBatchResponse handleRequest(SQSEvent event, Context context) { }
}
Amazon S3
import com.amazonaws.services.lambda.runtime.events.S3Event;
public class UnicornDocumentHandler implements RequestHandler<S3Event, String> {
@Override
public String handleRequest(S3Event event, Context context) { }
}
Before we dive deeper into best practices, let's take a look at the history of Java and computing which will help understand why AWS Lambda specific best practices are necessary.