Community contributed extensions

Play! Framework RabbitMQ Module

Felipe Oliveira http://mashup.fm http://geeks.aretotally.in http://twitter.com/_felipera

1) Installation

play install rabbitmq

2) RabbitMQ

Download RabbitMQ from http://www.rabbitmq.com/server.html.
Unzip the distribution, go to folder sbin and run “./rabbitmq-server”.
It should be running on port 5762 by default. The default user “guest” and password is “guest”.

3) Configuration

rabbitmq.host=localhost
rabbitmq.port=5672
rabbitmq.vhost=/
rabbitmq.user=guest
rabbitmq.password=guest
rabbitmq.exchangeType=direct
rabbitmq.durable=true
rabbitmq.autoAck=false
rabbitmq.basicQos=true

4) Define Message that will be used by the Queue (just a simple POJO)

public class SampleMessage implements Serializable {

private String field1;

private String field2;

public SampleMessage() {

}

public SampleMessage(String field1, String field2) {
super();
this.field1 = field1;
this.field2 = field2;
}

public String getField1() {
return field1;
}

public void setField1(String field1) {
this.field1 = field1;
}

public String getField2() {
return field2;
}

public void setField2(String field2) {
this.field2 = field2;
}

@Override
public String toString() {
return “SampleMessage [field1=” + field1 + “, field2=” + field2 + “]”;
}

}

5) Publish a Message

public static void publish(SampleMessage q) {
RabbitMQPublisher.publish(“myQueue”, q);
render(q);
}

6) Creating a Message Consumer

@OnApplicationStart(async = true)
public class RabbitMQSampleConsumer extends RabbitMQConsumer {

protected void consume(SampleMessage message) {
System.out.println(“******************************”);
System.out.println(“* Message Consumed: ” + message);
System.out.println(“******************************”);
}

protected String queue() {
return “myQueue”;
}

protected Class getMessageType() {
return SampleMessage.class;
}
}

7) Firehose – Another way to publish messages in batch

@OnApplicationStart(async = true)
public class RabbitMQSampleFirehose extends RabbitMQFirehose {

public int count = 0;

protected List getData(int n) throws Exception {
if ( count >= 10 ) {
return null;
}
List results = new ArrayList();
for (int i = 0; i < n; i++) {
results.add(new SampleMessage(“field1”, “field2”));
count++;
}
return results;
}

protected int batchSize() {
return 2;
}

protected String queueName() {
return “myQueue”;
}

}

Source Code

The source code is available on Github at https://github.com/feliperazeek/play-rabbitmq.