The ActiveMQ jar’s come with the AMQP 1.0 protocol, which doesn’t work against a RabbitMQ AMQP version 0.9.1 broker. As such, we use a spring jar to get this to work, thanks to this link.
Very simple example of this.
Maven pom.xml file…
4.0.0 com.express.it.arch.poc.amqp amqppoc jar 1.0-SNAPSHOT amqppoc http://maven.apache.org junit junit 3.8.1 test org.springframework.amqp spring-rabbit 1.5.2.RELEASE org.apache.maven.plugins maven-assembly-plugin com.yourcompany.it.arch.poc.amqp.App jar-with-dependencies
Java class for test…
package com.express.it.arch.poc.amqp; import org.springframework.amqp.core.*; import org.springframework.amqp.rabbit.core.*; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitAdmin; public class App { public static void main (String args[]) throws Exception { App a = new App(); a.createExchange("foo"); a.sendMessage("i came, i saw, i conquered"); Thread.sleep(5000); a.receiveMessage(); } private void createExchange(final String identifier) { final CachingConnectionFactory cf = new CachingConnectionFactory(5672); cf.setUsername("admin"); cf.setPassword("admin"); final RabbitAdmin admin = new RabbitAdmin(cf); final Queue queue = new Queue("myQueue", false); admin.declareQueue(queue); final TopicExchange exchange = new TopicExchange("myExchange"); admin.declareExchange(exchange); admin.declareBinding(BindingBuilder.bind(queue).to(exchange).with("#")); cf.destroy(); } private void deleteExchange() { final CachingConnectionFactory cf = new CachingConnectionFactory(5672); final RabbitAdmin admin = new RabbitAdmin(cf); admin.deleteExchange("myExchange"); cf.destroy(); } public void sendMessage(final String message) throws Exception { final CachingConnectionFactory cf = new CachingConnectionFactory(5672); cf.setUsername("admin"); cf.setPassword("admin"); final RabbitTemplate template = new RabbitTemplate(cf); template.convertAndSend("myExchange", "#", message); cf.destroy(); } public void receiveMessage() throws Exception { final CachingConnectionFactory cf = new CachingConnectionFactory(5672); cf.setUsername("admin"); cf.setPassword("admin"); final RabbitTemplate template = new RabbitTemplate(cf); String s = (String)template.receiveAndConvert("myQueue"); System.out.println("Message received = " + s); cf.destroy(); } }
Run build…
mvn clean compile assembly:single
Run test…
java -cp target\amqppoc-1.0-SNAPSHOT-jar-with-dependencies.jar com.express.it.arch.poc.amqp.App
You should see the message on the command line after five seconds. If you can GET the message in the RabbitMQ UI, available at http://localhost:15672/#/queues/myQueue, before the five seconds elapses, you should see the following…