I configured my RabbitMQ to use the following message converter: Jackson2JsonMessageConverter. However, it created a problem: when the producer sends message as a JSON String, the consumer received this String double-encoded.
Example:
The string sent by producer: "message": "Hello World!"
The string received by consumer: ""message": "Hello World!""
What I tried:
One of the solutions is to remove the Jackson2JsonMessageConverter from my RabbitMQ configuration, however I need Jackson2JsonMessageConverter because one of my other producers sends List<List<MyObject>>
to the queue, and I want to be able to deserialize it. So, removing Jackson2JsonMessageConverter is not going to be a valid solution for me.
RabbitMQConfig.java:
package dev.abu.screener_backend.rabbitmq;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
@Bean
public AmqpAdmin amqpAdmin(CachingConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
@Bean
public RabbitTemplate rabbitTemplate(CachingConnectionFactory connectionFactory) {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setMessageConverter(jacksonConverter());
return rabbitTemplate;
}
@Bean
public Jackson2JsonMessageConverter jacksonConverter() {
return new Jackson2JsonMessageConverter();
}
}
Methods from RabbitMQService.java to create queues, consumers and listeners:
public void createQueue(String queueName) {
amqpAdmin.declareQueue(new Queue(queueName, false, true, true));
}
public void createConsumer(String queueName) {
DirectMessageListenerContainer container = new DirectMessageListenerContainer(connectionFactory);
container.setQueueNames(queueName);
container.setMessageListener(getListener());
container.start();
}
public MessageListener getListener() {
return (Message message) -> {
String payload = new String(message.getBody());
System.out.println(payload);
// and doing something here with payload ...
};
}
And finally, this is how my producers sends a message to a queue:
String data =
"""
"message": "Hello World!"
"""; // this is example json
rabbitTemplate.convertAndSend(queue, data);
Any help will be appreciated! Thank you so much in advance!