Amazon Simple Notification Service (SNS) is a fully managed pub/sub messaging and mobile notifications service for coordinating the delivery of messages to subscribing endpoints and clients. One can get started with Amazon SNS using AWS console or AWS CLI or AWS SDK. One example of how Amazon SNS can be used is the following:
In this post, you will learn about how to publish a message to Amazon SNS Topic using a Spring Boot and Java AWS SDK app. The message can be a simple text message or a JSON message.
Pay attention to some of the following:
@SpringBootApplication public class RecruiterbotApplication implements CommandLineRunner { @Autowired PublisherService publisherService; public static void main(String[] args) { SpringApplication app = new SpringApplication(RecruiterbotApplication.class); app.run(args); } @Override public void run(String... arg0) throws IOException, URISyntaxException { try { this.publisherService.publish("{\"mobileno\": \"+919996019206\", \"message\": \"Hello Ajitesh! How have you been doing? Hope you are doing great. Good bye!\"}", PublisherService.TOPIC_INTERVIEWSTATUS); } catch (TopicNotSupportedException e) { e.printStackTrace(); } } }
Pay attention to the Publish API which takes message and topic name for publishing the message to an appropriate topic.
public interface PublisherService { // // Name of the topic // public static final String TOPIC_INTERVIEWSTATUS = "interview_status"; // // Publish Message API // void publish(String message, String topic) throws TopicNotSupportedException; }
Pay attention to some of the following in the implementation given below:
this.amazonSNS = AmazonSNSClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(sessionCredentials)).build();
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicSessionCredentials; import com.amazonaws.services.sns.AmazonSNS; import com.amazonaws.services.sns.AmazonSNSClientBuilder; import com.amazonaws.services.sns.model.PublishRequest; import com.amazonaws.services.sns.model.PublishResult; @Service public class AmazonSNSPublisherService implements PublisherService { private AmazonSNS amazonSNS; private String snsTopicInterviewStatusARN; @Autowired public AmazonSNSPublisherService(BasicSessionCredentials sessionCredentials, String snsTopicInterviewStatusARN) { this.amazonSNS = AmazonSNSClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(sessionCredentials)).build(); this.snsTopicInterviewStatusARN = snsTopicInterviewStatusARN; } @Override public void publish(String message, String topic) throws TopicNotSupportedException { // // Get Appropriate Topic ARN // String snsTopic = getTopicARN(topic); // // Create Publish Message Request with TopicARN and Message // PublishRequest publishRequest = new PublishRequest(snsTopic, message); // // Publish the message // PublishResult publishResult = this.amazonSNS.publish(publishRequest); // // Evaluate the result: Print MessageId of message published to SNS topic // System.out.println("MessageId - " + publishResult.getMessageId()); } private String getTopicARN(String topic) throws TopicNotSupportedException { switch(topic) { case TOPIC_INTERVIEWSTATUS: return this.snsTopicInterviewStatusARN; default: throw new TopicNotSupportedException("No matching topic supported!"); } } }
Pay attention to some of the following:
@Configuration @PropertySource("classpath:application.properties") public class AWSAppConfig { private static final Integer TEMPORARY_CREDENTIALS_DURATION_DEFAULT = 7200; @Value("${aws.temporary.credentials.validity.duration}") String credentialsValidityDuration; @Value("${aws.sns.topic.interviewstatus.ARN}") String snsTopicInterviewStatusARN; @Bean(name = "snsTopicInterviewStatusARN") public String snsTopcARN() { return this.snsTopicInterviewStatusARN; } @Bean(name = "sessionCredentials") public BasicSessionCredentials sessionCredentials() { AWSSecurityTokenServiceClient sts_client = (AWSSecurityTokenServiceClient) AWSSecurityTokenServiceClientBuilder.defaultClient(); GetSessionTokenRequest session_token_request = new GetSessionTokenRequest(); if(this.credentialsValidityDuration == null || this.credentialsValidityDuration.trim().equals("")) { session_token_request.setDurationSeconds(TEMPORARY_CREDENTIALS_DURATION_DEFAULT); } else { session_token_request.setDurationSeconds(Integer.parseInt(this.credentialsValidityDuration)); } GetSessionTokenResult session_token_result = sts_client.getSessionToken(session_token_request); Credentials session_creds = session_token_result.getCredentials(); BasicSessionCredentials sessionCredentials = new BasicSessionCredentials( session_creds.getAccessKeyId(), session_creds.getSecretAccessKey(), session_creds.getSessionToken()); return sessionCredentials; } }
Pay attention to the ARN URI of the topic. It is read from AWS SNS console.
# # Amazon SNS Topic # aws.sns.topic.interviewstatus.ARN = arn:aws:sns:us-east-1:165412123501:interview_status
In this post, you learned about creating a sample/example application which publishes a message to AWS SNS Topic using Spring Boot and Java.
Did you find this article useful? Do you have any questions or suggestions about this article in relation to publishing the message to Amazon SNS Topic using a Spring Boot and Java app? Leave a comment and ask your questions and I shall do my best to address your queries.
In recent years, artificial intelligence (AI) has evolved to include more sophisticated and capable agents,…
Adaptive learning helps in tailoring learning experiences to fit the unique needs of each student.…
With the increasing demand for more powerful machine learning (ML) systems that can handle diverse…
Anxiety is a common mental health condition that affects millions of people around the world.…
In machine learning, confounder features or variables can significantly affect the accuracy and validity of…
Last updated: 26 Sept, 2024 Credit card fraud detection is a major concern for credit…