LavinMQ with Java

An excellent Java AMQP library has been developed by RabbitMQ. The full API documentation for the library can be found here.

Java with amqp-client

Begin to add the AMQP library as an dependency in your pom.xml file (use the latest version):

<dependency>
  <groupId>com.rabbitmq</groupId>
  <artifactId>amqp-client</artifactId>
  <version>3.3.4</version>
</dependency>

Set a HOST_URL environment variable to your local LavinMQ instance or to a hosted LavinMQ setup.

Create a ConnectionFactory and configure it with the URL. All connections are created from this factory and on the connection we create a Channel.

Declare a queue and publish a message to the “default exchange” with the queue name as routing key. This is a shortcut as all queues by default a bound to the “default queue” with the it’s name as routing parameter.

Then start a consumer which listens to that queue prints out the message body to the console.

The full code can be seen at github.com/cloudamqp/java-amqp-example.

Code example Publish and subscribe

public static void main(String[] args) throws Exception {
  String uri = System.getenv("HOST_URL");
  if (uri == null) uri = "amqp://guest:guest@localhost";

  ConnectionFactory factory = new ConnectionFactory();
  factory.setUri(uri);

  //Recommended settings
  factory.setRequestedHeartbeat(30);
  factory.setConnectionTimeout(30000);

  Connection connection = factory.newConnection();
  Channel channel = connection.createChannel();

  String queue = "hello";     //queue name
  boolean durable = false;    //durable - RabbitMQ will never lose the queue if a crash occurs
  boolean exclusive = false;  //exclusive - if queue only will be used by one connection
  boolean autoDelete = false; //autodelete - queue is deleted when last consumer unsubscribes

  channel.queueDeclare(queue, durable, exclusive, autoDelete, null);
  String message = "Hello CloudAMQP!";

  String exchangeName = "";
  String routingKey = "hello";
  channel.basicPublish(exchangeName, routingKey, null, message.getBytes());
  System.out.println(" [x] Sent '" + message + "'");

  QueueingConsumer consumer = new QueueingConsumer(channel);
  channel.basicConsume(queue, true, consumer);

  while (true) {
    QueueingConsumer.Delivery delivery = consumer.nextDelivery();
    message = new String(delivery.getBody());
    System.out.println(" [x] Received '" + message + "'");
  }
}