Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.IllegalArgumentException when publishing a message with RabbitTemplate

I try to publish a message on a Queue with RabbitTemplate (using Spring Boot) and I got this message. I already tried to search for a solution.

Caused by: java.lang.IllegalArgumentException: SimpleMessageConverter only supports String, byte[] and Serializable payloads, received: com.example.demo.SimpleMessage

Maybe this part of code can help

@Override
    public void run(String...strings) throws Exception {

        SimpleMessage simpleMessage = new SimpleMessage();
        simpleMessage.setName("FirstMessage");
        simpleMessage.setDescription("simpleDescription");

        rabbitTemplate.convertAndSend("TestExchange", "testRouting", simpleMessage);
    }

I appreciate any collaboration.

like image 269
el-chico Avatar asked Mar 15 '19 19:03

el-chico


Video Answer


2 Answers

The problem is that your class SimpleMessage does not implement Serializable.

RabbitTemplate.convertAndSend uses SimpleMessageConveter to convert your message into an amqp message. However SimpleMessageConverter requires that message to implement the interface Serializable.

Your SimpleMessage class should look like follows:

public class SimpleMessage implements Serializable {
    ... your code here
}

You can learn more about Serializable objects here.

like image 148
Dylan Avatar answered Oct 10 '22 18:10

Dylan


There is another solution: use a different implementation of the MessageConverter instead of default SimpleMessageConverter.

For example, Jackson2JsonMessageConverter:

public RabbitTemplate jsonRabbitTemplate(ConnectionFactory connectionFactory, ObjectMapper mapper) {
    final var jsonRabbitTemplate = new RabbitTemplate(connectionFactory);
    jsonRabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter(mapper));
    return jsonRabbitTemplate;
}
like image 44
Evgene Krylov Avatar answered Oct 10 '22 16:10

Evgene Krylov