Lambda project code (Java)

The Maven pom.xml file of the project should also define the following dependency:

<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-sqs</artifactId>
<version>${aws.sdk.version}</version>
</dependency>

We can create a Java Lambda project with the following structure:

Note that we do not have request and response domain objects, as AWS will be invoking the Lambda and passing a predefined event object based on a trigger we configure.

SnsService.java is the interface for our service class. This is not a requirement—you can directly use the implementation class or even embed all logic within Lambda handler class itself:

public interface SnsService {
Boolean processEvent(SNSEvent event, String outputQueueURL, LambdaLogger logger);
}

SqsServiceImpl.java is the actual service implementation. 

We can retrieve messages from the input SNSEvent and create a collection of SendMessageBatchRequestEntry objects:

Collection<SendMessageBatchRequestEntry> entries = new ArrayList<>();

int idVal = 1;
for (SNSRecord r : event.getRecords()) {
logger.log("Adding message: " + r.getSNS().getMessage());
entries.add(new SendMessageBatchRequestEntry("id_" + idVal, r.getSNS().getMessage()));
idVal++;
}

We can create and send a batch request to the output queue, as follows:

final SendMessageBatchRequest sendBatchRequest = new SendMessageBatchRequest()
.withQueueUrl(outputQueueURL)
.withEntries(entries);
this.sqsClient.sendMessageBatch(sendBatchRequest);

LambdaSnsEventHandler.java is our Lambda handler class where we initialize the SQS client and pass it to the service class along with the SNSEvent we received. 

We can initialize the SQS Client as follows:

private final AmazonSQS sqsClient;

public LambdaSnsEventHandler() {
this.sqsClient = AmazonSQSClientBuilder.standard()
.withRegion(System.getenv("AWS_REGION"))
.build();
}

We then invoke the service method, passing the client along with the SNSEvent object:

public Boolean handleRequest(final SNSEvent snsEvent, final Context context) {
context.getLogger().log("Received SQS event: " + snsEvent);

final SnsService snsService = new SnsServiceImpl(this.sqsClient);
return snsService.processEvent(snsEvent, System.getenv("SPC_OUTPUT_QUEUE_URL"), context.getLogger());

}

We will use an environment variable to specify the name of the output queue. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.26.108