This sample create a Durable Exchange, Queue and a Message. You will have to start the consumer first before you start the for the first time.
For more information on AMQP, Exchanges, Queues, read this excellent tutorial
http://blogs.digitar.com/jjww/2009/01/rabbits-and-warrens/
+++++++++++++++++RabbitMQProducer.java+++++++++++++++++++++++++++
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.*;
public class RabbitMQProducer {
public static void main(String []args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("guest");
factory.setPassword("guest");
factory.setVirtualHost("/");
factory.setHost("127.0.0.1");
factory.setPort(5672);
Connection conn = factory.newConnection();
Channel channel = conn.createChannel();
String exchangeName = "myExchange";
String routingKey = "testRoute";
byte[] messageBodyBytes = "Hello, world!".getBytes();
channel.basicPublish(exchangeName, routingKey
,MessageProperties.PERSISTENT_TEXT_PLAIN, messageBodyBytes) ;
channel.close();
conn.close();
}
}
+++++++++++++++++RabbitMQConsumer.java+++++++++++++++++++++++++++
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.*;
public class RabbitMQConsumer {
public static void main(String []args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("guest");
factory.setPassword("guest");
factory.setVirtualHost("/");
factory.setHost("127.0.0.1");
factory.setPort(5672);
Connection conn = factory.newConnection();
Channel channel = conn.createChannel();
String exchangeName = "myExchange";
String queueName = "myQueue";
String routingKey = "testRoute";
boolean durable = true;
channel.exchangeDeclare(exchangeName, "direct", durable);
channel.queueDeclare(queueName, durable,false,false,null);
channel.queueBind(queueName, exchangeName, routingKey);
boolean noAck = false;
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(queueName, noAck, consumer);
boolean runInfinite = true;
while (runInfinite) {
QueueingConsumer.Delivery delivery;
try {
delivery = consumer.nextDelivery();
} catch (InterruptedException ie) {
continue;
}
System.out.println("Message received"
+ new String(delivery.getBody()));
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}
channel.close();
conn.close();
}
}