Curious George
Curious George

Reputation: 209

Java Spring RabbitMq consumer

I am trying to create a RabbitMq consumer in Java Spring framework. Where I need to implement RabbitMq RPC model, so basically consumer shall receive some message from RabbitMq broker, process it, and send it back to the associated reply queue.

Can somebody please point me a neat sample code which implements this requirement in Spring ?

Thanks in advance.

Upvotes: 0

Views: 2960

Answers (2)

Curious George
Curious George

Reputation: 209

Thanks Gary, it worked for me. I used @RabbitListener annotation.

Strangely it only works when I provide queue alone, However specifying a binding of exchange, routing key and queue doesn't work. Not sure what the issue here.

Here is client code snippet in python.

#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='myQueue',durable='true')

channel.basic_publish(exchange='myExchange',
                      routing_key='rpc_queue',
                      body='Hello World!')
print " [x] Sent 'Hello World!'"
connection.close()

Here is spring consumer code.

@RabbitListener(
        bindings = @QueueBinding(
        value = @Queue(value = "myQueue", durable = "true"),
        exchange = @Exchange(value = "myExchange"),
        key = "rpc_queue")
  )
  public void processOrder(Message message) {
        String messageBody= new String(message.getBody());
        System.out.println("Received : "+messageBody);
}

Not sure whats going wrong with this binding.

Upvotes: 0

Gary Russell
Gary Russell

Reputation: 174554

Consider using the Spring AMQP Project.

See the documentation about async consumers. You just need to implement a POJO method and use a MessageListenerAdapter (which is inserted by default when using XML configuration) - if your POJO method returns a result, the framework will automatically send the reply to the replyTo in the inbound message, which can be a simple queue name, or exchange/routingKey.

<rabbit:listener-container connection-factory="rabbitConnectionFactory">
    <rabbit:listener queues="some.queue" ref="somePojo" method="handle"/>
</rabbit:listener-container>

public class SomePojo {
    public String handle(String in) {
        return in.toUpperCase();
    }
}

Or, you can use the annotation @RabbitListener in your POJO - again, see the documentation.

Upvotes: 1

Related Questions