简体   繁体   中英

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 ???);

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM