RabbitMQ tutorial - "Hello World!"
Introduction
Prerequisites
This tutorial assumes RabbitMQ is installed and running on
localhost on the standard port (5672). In case you
use a different host, port or credentials, connections settings would require
adjusting.
Where to get help
If you're having trouble going through this tutorial you can contact us through GitHub Discussions or RabbitMQ community Discord.
RabbitMQ is a message broker: it accepts and forwards messages. You can think about it as a post office: when you put the mail that you want posting in a post box, you can be sure that the letter carrier will eventually deliver the mail to your recipient. In this analogy, RabbitMQ is a post box, a post office, and a letter carrier.
The major difference between RabbitMQ and the post office is that it doesn't deal with paper, instead it accepts, stores, and forwards binary blobs of data ‒ messages.
RabbitMQ, and messaging in general, uses some jargon.
-
Producing means nothing more than sending. A program that sends messages is a producer :
-
A queue is the name for the post box in RabbitMQ. Although messages flow through RabbitMQ and your applications, they can only be stored inside a queue. A queue is only bound by the host's memory & disk limits, it's essentially a large message buffer.
Many producers can send messages that go to one queue, and many consumers can try to receive data from one queue.
This is how we represent a queue:
-
Consuming has a similar meaning to receiving. A consumer is a program that mostly waits to receive messages:
Note that the producer, consumer, and broker do not have to reside on the same host; indeed in most applications they don't. An application can be both a producer and consumer, too.
"Hello World"
(using the AMQP 1.0 Java client)
In this part of the tutorial we'll write two programs in Java; a producer that sends a single message, and a consumer that receives messages and prints them out. We'll gloss over some of the detail in the Java API, concentrating on this very simple thing just to get started. It's the "Hello World" of messaging.
In the diagram below, "P" is our producer and "C" is our consumer. The box in the middle is a queue - a message buffer that RabbitMQ keeps on behalf of the consumer.
The AMQP 1.0 Java client library
RabbitMQ speaks multiple protocols. This tutorial uses AMQP 1.0 over the same port as AMQP 0-9-1 (5672 by default). It requires RabbitMQ 4.0 or later.
Use the RabbitMQ AMQP 1.0 Java client (
com.rabbitmq.client:amqp-client), not the classic AMQP 0-9-1 client (com.rabbitmq:amqp-client). See AMQP 1.0 client libraries and the client reference.Add the dependency to your build, for example with Maven:
<dependency><groupId>com.rabbitmq.client</groupId><artifactId>amqp-client</artifactId><version>0.10.0</version></dependency>Runnable sources for this tutorial series live alongside the other ports in the RabbitMQ tutorials repository (
java-amqpdirectory).
Now we have the client on the classpath, we can write some code.
Sending
We'll call our message publisher (sender) Send and our message consumer (receiver)
Recv. The publisher will connect to RabbitMQ, send a single message,
then exit.
In
Send.java,
we need some classes imported:
import com.rabbitmq.client.amqp.Connection;
import com.rabbitmq.client.amqp.Environment;
import com.rabbitmq.client.amqp.Publisher;
import com.rabbitmq.client.amqp.impl.AmqpEnvironmentBuilder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
Set up the class and name the queue:
public class Send {
private static final String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
...
}
}
Then create an environment
and a connection. The environment holds shared settings; each connection targets the broker.
Here the URI points at a broker on the local machine with the default virtual host (%2f is /).
Environment environment = new AmqpEnvironmentBuilder()
.connectionSettings()
.uri("amqp://guest:guest@localhost:5672/%2f")
.environmentBuilder()
.build();
Connection connection = environment.connectionBuilder().build();
The connection abstracts the socket connection and takes care of protocol negotiation and authentication. To connect to a different host, change the host (and credentials) in the URI.
connection.management().queue(QUEUE_NAME).quorum().queue().declare();
RabbitMQ still exposes the AMQ 0.9.1 model (queues, exchanges, bindings) for topology. Declare a
quorum queue before publishing. The declare API uses a fluent chain; for quorum queues it must end
with .quorum().queue().declare(). Declaring a queue is idempotent: it is only created if it does not
already exist.
To send a message, create a publisher addressed at the queue, build a message, and call publish.
The broker reports the outcome asynchronously; wait on a latch so the program does not exit before feedback
arrives. A successful publish has status Publisher.Status.ACCEPTED:
try (Publisher publisher = connection.publisherBuilder().queue(QUEUE_NAME).build()) {
String message = "Hello World!";
CountDownLatch latch = new CountDownLatch(1);
publisher.publish(
publisher.message(message.getBytes(StandardCharsets.UTF_8)),
context -> {
if (context.status() == Publisher.Status.ACCEPTED) {
System.out.println(" [x] Sent '" + message + "'");
}
latch.countDown();
});
if (!latch.await(5, TimeUnit.SECONDS)) {
throw new IllegalStateException("Timed out waiting for publish outcome");
}
}
Here's the whole Send.java class.
Sending doesn't work!
If this is your first time using RabbitMQ and you don't see the "Sent" message then you may be left scratching your head wondering what could be wrong. Maybe the broker was started without enough free disk space (by default it needs at least 50 MB free) and is therefore refusing to accept messages. Check the broker log file to see if there is a resource alarm logged and reduce the free disk space threshold if necessary. The Configuration guide will show you how to set
disk_free_limit.
Receiving
That's it for our publisher. Our consumer listens for messages from RabbitMQ, so unlike the publisher which publishes a single message, we'll keep the consumer running to listen for messages and print them out.
The code in Recv.java uses the same environment and connection setup. Open a connection, then declare the same queue so the consumer can start before the publisher:
import com.rabbitmq.client.amqp.Connection;
import com.rabbitmq.client.amqp.Consumer;
import com.rabbitmq.client.amqp.Environment;
import com.rabbitmq.client.amqp.impl.AmqpEnvironmentBuilder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
public class Recv {
private static final String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
Environment environment = new AmqpEnvironmentBuilder()
.connectionSettings()
.uri("amqp://guest:guest@localhost:5672/%2f")
.environmentBuilder()
.build();
Connection connection = environment.connectionBuilder().build();
connection.management().queue(QUEUE_NAME).quorum().queue().declare();
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
Consumer consumer = connection.consumerBuilder()
.queue(QUEUE_NAME)
.messageHandler((context, message) -> {
String text = new String(message.body(), StandardCharsets.UTF_8);
System.out.println(" [x] Received '" + text + "'");
context.accept();
})
.build();
new CountDownLatch(1).await();
}
}
Note that we declare the queue here as well. Because we might start the consumer before the publisher, we want to make sure the queue exists before we try to consume messages from it.
Why not use try-with-resources on Environment and Connection in the consumer? Closing them would stop the process as soon as the try block ends. The sample keeps the consumer running; use Ctrl+C to stop the JVM (or extend the example to close resources on shutdown).
With AMQP 1.0, the consumer must settle each message (accept, discard, or requeue). Here we call context.accept() after printing the body.
Here's the whole Recv.java class.
Putting it all together
Create a pom.xml that includes the client and the Exec Maven Plugin so you can run the classes by name:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.rabbitmq.examples</groupId>
<artifactId>amqp10-tutorials</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.release>11</maven.compiler.release>
</properties>
<dependencies>
<dependency>
<groupId>com.rabbitmq.client</groupId>
<artifactId>amqp-client</artifactId>
<version>0.10.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<mainClass>${exec.mainClass}</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
Place Send.java and Recv.java under src/main/java/, then in one terminal run the consumer:
mvn -q compile exec:java -Dexec.mainClass=Recv
Then run the publisher:
mvn -q compile exec:java -Dexec.mainClass=Send
The consumer will print the message it gets from the publisher via RabbitMQ. The consumer will keep running, waiting for messages (use Ctrl+C to stop it), so try running the publisher from another terminal.
Listing queues
You may wish to see what queues RabbitMQ has and how many messages are in them. You can do it (as a privileged user) using the
rabbitmqctltool:sudo rabbitmqctl list_queuesOn Windows, omit the sudo:
rabbitmqctl.bat list_queues
Time to move on to part 2 and build a simple work queue.