Lambda project code (Java)

In this recipe, we will write our logic within the Lambda handler itself without any service classes. I generally tend to create service classes as I primarily come from an enterprise Java development background. This is, however, not a requirement for Lambdas, and in many cases it might be better to simply code the logic within the Lambda handler itself. You can follow whatever approach you feel comfortable with. There might be also a preferred approach for most teams. 

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

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

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 topicArn;
private String message;
}

There is no Response object as we are simply returning a String value as response.

LambdaSnsPublishHandler.java is our Lambda handler class, where we initialize the SNS client and publish the message. 

We can initialize the SNS client as follows:

private final AmazonSNS snsClient;
public LambdaSnsPublishHandler() {
this.snsClient = AmazonSNSClientBuilder.standard()
.withRegion(System.getenv("AWS_REGION"))
.build();
}

We can then publish the message directly from the handler:

public String handleRequest(final Request request, final Context context) {
final PublishResult result;
try {
PublishRequest publishRequest = new PublishRequest(request.getTopicArn(), request.getMessage());
result = snsClient.publish(publishRequest);
} catch (Exception e) {
return "Exception occurred: " + e.getMessage();
}

    return "Message Id: " + result.getMessageId();
}
..................Content has been hidden....................

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