A lean starting point for building, testing and deploying AWS Lambdas with Java. This project serves as a reference implementation for serverless BCE (Boundary-Control-Entity) architecture.
A simple Java AWS Lambda without any AWS dependencies:
package airhacks.lambda.example.boundary;
public class EventListener {
static String message = System.getenv("message");
public void onEvent(Object awsEvent) {
Log.info("event received: %s", awsEvent);
var domainEvent = extract(awsEvent);
EventProcessor.process(domainEvent);
}
static ExampleEvent extract(Object event) {
return new ExampleEvent(event.toString());
}
}
...deployed with AWS Cloud Development Kit:
import software.amazon.awscdk.services.lambda.*;
Function createFunction(String functionName, String functionHandler, Map<String,String> configuration, int memory, int timeout) {
return Function.Builder.create(this, functionName)
.runtime(Runtime.JAVA_21)
.architecture(Architecture.ARM_64)
.code(Code.fromAsset("../lambda/target/function.jar"))
.handler(functionHandler)
.memorySize(memory)
.functionName(functionName)
.environment(configuration)
.timeout(Duration.seconds(timeout))
.tracing(Tracing.ACTIVE)
.build();
}
...provisioned with maven and cdk:
cd lambda && mvn clean package
cd ../cdk && mvn clean package && cdk deploy
...and (blackbox) tested with AWS SDK for Java 2.x:
@BeforeEach
public void initClient() {
var credentials = DefaultCredentialsProvider.builder().build();
this.client = LambdaClient.builder()
.credentialsProvider(credentials)
.build();
}
@Test
public void invokeLambdaAsynchronously() {
var json = """
{
"user":"duke"
}
""";
var payload = SdkBytes.fromUtf8String(json);
var request = InvokeRequest.builder()
.functionName("airhacks_EventListener")
.payload(payload)
.invocationType(InvocationType.REQUEST_RESPONSE)
.build();
var response = this.client.invoke(request);
var error = response.functionError();
assertNull(error);
var value = response.payload().asUtf8String();
Log.info("Function executed. Response: " + value);
}
Cold and "warm" starts of JavaScript and Java Lambdas:
The deployment is borrowed from: "Slightly Streamlined AWS Cloud Development Kit (CDK) Boilerplate"