简体   繁体   中英

Spring JMS json message converter

I have some problems to convert messages from RabbitMQ using spring-jms module. Previously I send my messages using Rest API endpoint, this endpoint send the message to RabbitMQ queue and process it using @JmsListener methods.

Internally this behaviour add a field to determine the Java type, managed by Spring libraries. However now I want to avoid the Rest API call because it's not necessary and I can send the message directly to RabbitMQ.

The problem is when spring try to convert JMS message for @JmsListener parameter. I didn't set the type on the message because the sender doesn't need that information but now I cannot convert it directly because MappingJackson2MessageConverter want a property for that.

How can I avoid this problem? I want to be able to process all message without needs to know the type in all the "senders".

Message converter bean:

   @Bean
   public MessageConverter jacksonJmsMessageConverter() {
      MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
      converter.setTargetType(MessageType.TEXT);
      converter.setTypeIdPropertyName("_type");
      return converter;
   }

Listener sample code:

 @JmsListener(concurrency = "listener.concurrency", destination = "queue.name", containerFactory = "container.factory")
 public void processFile(MyDtoClass dto) {
    ....
 }

Subclass the converter and override getJavaTypeForMessage() to return the type you want...

/**
 * Determine a Jackson JavaType for the given JMS Message,
 * typically parsing a type id message property.
 * <p>The default implementation parses the configured type id property name
 * and consults the configured type id mapping. This can be overridden with
 * a different strategy, e.g. doing some heuristics based on message origin.
 * @param message the JMS Message to set the type id on
 * @throws JMSException if thrown by JMS methods
 * @see #setTypeIdOnMessage(Object, javax.jms.Message)
 * @see #setTypeIdPropertyName(String)
 * @see #setTypeIdMappings(java.util.Map)
 */
protected JavaType getJavaTypeForMessage(Message message) throws JMSException {

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