In the previous recipes, we used a service interface and its implementation. In this recipe, we will create a Lambda function without a service class. As discussed in the previous chapter, you can follow any of the approaches that you prefer (or that your project prefers), but the underlying code will be the same.
Let's start by defining the dependency for the AWS Kinesis SDK for Java in the POM file, as shown in the following code:
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-kinesis</artifactId>
<version>${aws.sdk.version}</version>
</dependency>
The POM file also has dependencies for aws-lambda-java-core. The aws.sdk.version property is defined, along with other properties in the parent project POM , serverless-cookbook-parent-aws-java.
We can create the Java Lambda project with the following structure:
LambdaKinesisEventHandler.java can be implemented as follows:
public final class LambdaKinesisEventHandler implements RequestHandler<KinesisEvent, Boolean> {
public Boolean handleRequest(final KinesisEvent kinesisEvent, final Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Received Kinesis event: " + kinesisEvent);
logger.log("Number of records: " + kinesisEvent.getRecords().size());
try {
kinesisEvent.getRecords().forEach(r -> {
final KinesisEvent.Record kr = r.getKinesis();
logger.log("Record: " + kr.toString());
logger.log("Data: " + StandardCharsets.UTF_8.decode(kr.getData()).toString());
});
} catch (final Exception e) {
logger.log("There was an exception: " + e.getMessage());
return false;
}
return true;
}
}