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):


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

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

  //Recommended settings

  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 + "'");

Ready to take the next steps? Here are some things you should keep in mind:

Managed LavinMQ instance on CloudAMQP

LavinMQ has been built with performance and ease of use in mind - we've benchmarked a throughput of about 1,000,000 messages/sec. You can try LavinMQ without any installation hassle by creating a free instance on CloudAMQP. Signing up is a breeze.

Help and feedback

We welcome your feedback and are eager to address any questions you may have about this piece or using LavinMQ. Join our Slack channel to connect with us directly. You can also find LavinMQ on GitHub.