Tuesday, October 11, 2011

Sample Java client for RabbitMQ

Here you can find sample java client for RabbitMQ. I have taken this from Programming fun at startup blog. I have tried this and working
fine with out any issue.


Steps to follow :

1. Install RabbitMQ server : http://www.rabbitmq.com/install.html#debian

2. Download RabbitMQ client libraries : http://www.rabbitmq.com/java-client.html

3. Start the installed RabbitMQ Server

4. Use the downloaded client libraries for the following consumer and the sender.

5. Start the consumer first and then the Producer


-------------------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();
}
}


Another nice article on this can be found here.

No comments:

Post a Comment