Lambda project code (Java)

We will create a Lambda that gets triggered when messages are put into an SQS queue, and it will then send the message to another as a batch. 

Since we have already discussed Lambdas in detail earlier, I will show only important parts of the code and step details here. I will also not show error handling and other supportive code. Please refer to the code files for the complete code. 

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

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

The POM file also has dependencies for aws-lambda-java-core, and inherits from the parent project, serverless-cookbook-parent-aws-java.

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

The Request.java class will correspond to our input JSON:

@Data
public class Request {
private String queueName;
private String message;
}

Response.java will contain a field to send the response back to the invoker:

@Data
@AllArgsConstructor
public class Response {
private String message;
}

SqsService.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 the Lambda handler class itself:

public interface SqsService {
Response createQueueAndSendMessage(Request request, LambdaLogger logger);
}

SqsServiceImpl.java is the actual service implementation. 

We can create an SQS queue and retrieve its URL, as follows:

CreateQueueResult createResult = this.sqsClient.createQueue(request.getQueueName());
logger.log("Created queue: " + createResult.getQueueUrl());

We can also get the URL, as follows:

String queueUrl = this.sqsClient.getQueueUrl(request.getQueueName()).getQueueUrl();

We can create a SendMessageRequest and send a message, as follows:

SendMessageRequest sendMessageRequest = new SendMessageRequest()
.withQueueUrl(queueUrl)
.withMessageBody(request.getMessage())
.withDelaySeconds(5);
this.sqsClient.sendMessage(sendMessageRequest);

LambdaSqsSdkCreateSendHandler.java is our Lambda handler class where we initialize the SQS client and pass it to the service class. 

We can initialize the SQS client as follows:

private final AmazonSQS sqsClient;
public LambdaSqsSdkCreateSendHandler() {
this.sqsClient = AmazonSQSClientBuilder.standard()
.withRegion(System.getenv("AWS_REGION"))
.build();
}

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

public Response handleRequest(final Request request, final Context context) {
final SqsService sqsService = new SqsServiceImpl(this.sqsClient);
return sqsService.createQueueAndSendMessage(request, context.getLogger());
}
..................Content has been hidden....................

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