Very simple application classes (sender and receiver)
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
public class MessageSender {
@Autowired
private AmqpTemplate template;
public void send(String text) {
template.convertAndSend(text);
}
}
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
public class MessageHandler implements MessageListener {
@Override
public void onMessage(Message message) {
System.out.println("Received message: " + message);
}
}
and pretty standard application context
<context:annotation-config />
<bean id="rabbitConnectionFactory" class="org.springframework.amqp.rabbit.connection.SingleConnectionFactory"
p:username="guest" p:password="guest" p:virtualHost="/" p:port="5672">
<constructor-arg value="lab.ndpar.com" />
</bean>
<bean id="rabbitTemplate" class="org.springframework.amqp.rabbit.core.RabbitTemplate"
p:connectionFactory-ref="rabbitConnectionFactory"
p:routingKey="myRoutingKey"
p:exchange="myExchange" />
<bean id="messageSender" class="com.ndpar.spring.rabbitmq.MessageSender" />
<bean class="org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer"
p:connectionFactory-ref="rabbitConnectionFactory"
p:queueName="myQueue"
p:messageListener-ref="messageListener" />
<bean id="messageListener" class="com.ndpar.spring.rabbitmq.MessageHandler" />
That's it, simple and clean.
Resources
• Spring AMQP official page
• Source code for this blog