Wednesday, July 15, 2015

RabbitMQ client to subscribe to a queue in WSO2 Message Broker 3.0.0 using Java

Hi All,

WSO2 Message Broker 3.0.0 is a distributed message broker that provides reliable messaging.

This post will explain on how the RabbitMQ java client can be used to subscribe to a queue WSO2 Message Broker 3.0.0 with the help of Maven.

Add the RabbitMQ java client dependency

Add the following dependency the pom.xml file


The Code

Following is the implementation. See descriptions inline.

// The queue name
String queueName = "MyQueue";

// Creating the AMQP connection string for communication
ConnectionFactory factory = new ConnectionFactory();
final Connection connection = factory.newConnection();
final Channel channel = connection.createChannel();

// Creating the queue
channel.queueDeclare(queueName, true, false, false, null);

// Binding the queue to "" exchange. Exchanges cannot be declared in WSO2 MB 3.0.0.
channel.queueBind(queueName, "", queueName);

// Creating consumer
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(queueName, false, consumer);

// Shutdown hook handler
Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
        try {
            // Closing the connection
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            throw new RuntimeException(e);

// Accepting messages
while (true) {
    QueueingConsumer.Delivery delivery = consumer.nextDelivery();
    String message = new String(delivery.getBody());

    System.out.println("Message Received : " + message);

Click here to download the sample maven project.


No comments:

Post a Comment