2

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 ???);
ℛɑƒæĿᴿᴹᴿ
  • 4,983
  • 4
  • 38
  • 58
Bruno DZ
  • 43
  • 1
  • 6

3 Answers3

8

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);
JCompetence
  • 6,997
  • 3
  • 19
  • 26
0

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);
kenji
  • 763
  • 8
  • 14
0

In case you don't want to use attribute-based message filtering, and switch to payload-based message filtering, you can too. You simply have to set a subscription attribute named FilterPolicyScope to MessageBody, whereas the default is MessageAttributes. More info: https://aws.amazon.com/blogs/compute/introducing-payload-based-message-filtering-for-amazon-sns/

Otavio Ferreira
  • 755
  • 6
  • 11