Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set AWS SNS message attribute values with spring-cloud-aws-messaging or aws-java-sdk?

I have a standard SNS topic and I´ve set the "subscription filter policy" like this:

{
  "event": [
    "eventName"
  ]
}

When I publish a message through the AWS console using the attributes message, the message goes to the right SQS subscriber. So the subscription filter worked just fine.

Now I'm trying to do the same on my java code (Spring Boot).

I'm using the lib spring-cloud-aws-messaging which I understand is just a Wrapper of AWS JDK.

The problem is I can't figured out how to set the message attributes just like I did on AWS console.

Doesn´t matter the JSON format I sent to SNS the attributes always are in the body of the SNS message. I guess there is a specific method to set those attributes.

I found com.amazonaws.services.sns.model.MessageAttributeValue

I'm not sure if is the right class, also I couldn't understand how to publish the message and the attributes as the method publish doesn't accept it .

this.amazonSNS.publish(this.snsTopicARN, message, messageAttributes ???);
like image 420
Bruno DZ Avatar asked Oct 25 '25 09:10

Bruno DZ


2 Answers

According to official documentation, there is MessageAttributeValue.Builder, which matches what you need.

https://javadoc.io/static/software.amazon.awssdk/sns/2.10.37/software/amazon/awssdk/services/sns/model/MessageAttributeValue.Builder.html

Map<String, MessageAttributeValue> attributes = new HashMap<>();

attributes.put("event", MessageAttributeValue.builder()
        .dataType("String")
        .stringValue("eventName")
        .build());

PublishRequest request = PublishRequest.builder()
        .topicArn("yourTopic")
        .message("YourMessageBody")
        .messageAttributes(attributes)
        .build();

yourDefinedSnsClient.publish(request);
like image 65
JCompetence Avatar answered Oct 27 '25 23:10

JCompetence


If you want to use spring-cloud-aws you can do something like this:

SnsMessage snsMessage = SnsMessage.builder()
    .message("test")
    .build();

Map<String, Object> headers = new HashMap<>();
headers.put("event", "eventName");

this.notificationMessagingTemplate.convertAndSend(topicName, snsMessage, headers);
like image 39
kenji Avatar answered Oct 27 '25 22:10

kenji