How to remove JavaType in MessageAttributes when sending a message using SqsTemplate in Spring Cloud Aws 3.x

558 Views Asked by At

I'm using a SqsTemplate in Spring Cloud Aws 3.x to send messages to SQS.

When I receive a message from SQS, the object type I want to deserialize is DummyRequest, but the JavaType in MessageAttributes is String, so I use StringMessageConverter instead of MappingJackson2MessageConverter and the deserialization fails.

How can I remove the JavaType when sending messages from SqsTemplate to SQS?

I have seen the documentation at https://docs.awspring.io/spring-cloud-aws/docs/3.0.0-SNAPSHOT/reference/html/index.html#specifying-a-payload-class-for-receive-operations but I don't see how I can remove the JavaType.

The MessageAttributes look like this

    MessageAttributes={
        Content-type=MessageAttributeValue(StringValue=application/json, DataType=String), 
        JavaType=MessageAttributeValue(StringValue=java.lang.String, DataType=String), 
        contentType=MessageAttributeValue(StringValue=text/plain ;charset=UTF-8, DataType=String)}), 
        id=914fb72e-887e-4822-8e20-93a68b22b943, 
        Sqs_VisibilityTimeout=io.awspring.cloud.sqs.listener.QueueMessageVisibility@591afceb, 
        contentType=text/plain;charset=UTF-8, timestamp=1693990899688}]
1

There are 1 best solutions below

0
Văn Minh Nguyên On

I have a trick using the config for the consumer

@Primary
@Bean
public ObjectMapper om() {
  ObjectMapper om = new ObjectMapper();
  om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  return om;
}

@Bean
public SqsListenerConfigurer configurer(ObjectMapper objectMapper) {
  var defaultConverter = new MappingJackson2MessageConverter(
      new MimeType("application", "json"),
      new MimeType("application", "*+json"),
      new MimeType("text", "plain")
  );
  defaultConverter.setObjectMapper(objectMapper);
  return registrar -> {
    registrar.manageMessageConverters(converters -> {
      converters.clear();
      converters.add(defaultConverter);
    });
  };
}

Your consumer would be

@SqsListener(value = "queue-name")
public void consume(CustomEvent event) {

}