If using JSON Object to send and receive over RabbitMQ is this the cleanest way to send and receive? All that conversion seems inefficient.
Sending Code
JSONObject messageJSON = new JSONObject();
messageJSON.put("messageId", "testId");
messageJSON.put("NodeId", "testNode");
template.convertAndSend("TEST-EXCHANGE",
"routing.test", messageJSON.toJSONString()
.getBytes());
Receive Code
public class Listener implements MessageListener {
@Override
public void onMessage(Message message) {
String recmessage = new String(message.getBody());
JSONObject obj = (JSONObject) JSONValue.parse(recmessage);
System.out
.println("Message Received " + (String) obj.get("messageId"));
}
}
Solution From Answer given
You need to add the Dependency of Jackson. Below is maven:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1</version>
</dependency>
Add to the Spring Config
<bean id="amqpCorrectionTemplate" class="org.springframework.amqp.rabbit.core.RabbitTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="messageConverter">
<bean
class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter">
</bean>
</property>
</bean>
Add to the message Listener
Jackson2JsonMessageConverter jmc = new Jackson2JsonMessageConverter();
JSONObject obj = (JSONObject) jmc.fromMessage(message);
Sending Code Only send the JSON Object passed in.
template.convertAndSend("TEST-EXCHANGE",
"routing.test", messageJSON);
This wrong question: the AMQP protocol (as any other wire-based) gets deal just with bytes, so it's up to your application how to convert to byte[]
and back (if it is Java everywhere, of course).
From other side it would be better to your configuration based on the out-of-the- box converters. For example Jackson2JsonMessageConverter
.
See more information in the Documentation.