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 Kotlin Client)
In this part of the tutorial we'll write two programs in Kotlin; 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 Kotlin 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 Kotlin client library
RabbitMQ speaks multiple protocols. This tutorial uses AMQP 0-9-1, which is an open, general-purpose protocol for messaging. There are a number of clients for RabbitMQ in many different languages. We'll use the Kourier client library for Kotlin.
Kourier is a modern, coroutine-based AMQP 0-9-1 client for Kotlin. To use it in your project, add the following dependency:
Gradle (Kotlin DSL):
dependencies {
implementation("dev.kourier:amqp-client:x.x.x")
}Gradle (Groovy DSL):
dependencies {
implementation 'dev.kourier:amqp-client:x.x.x'
}Maven:
<dependency>
<groupId>dev.kourier</groupId>
<artifactId>amqp-client-jvm</artifactId>
<version>x.x.x</version>
</dependency>We recommend checking the Kourier release page for the latest version number, replacing
x.x.xabove with the latest stable release.
Now we have the Kotlin client library set up, we can write some code.
Sending
We'll call our message publisher (sender) send and our message consumer (receiver)
receive. The publisher will connect to RabbitMQ, send a single message,
then exit.
We need some imports:
import dev.kourier.amqp.Properties
import dev.kourier.amqp.connection.amqpConfig
import dev.kourier.amqp.connection.createAMQPConnection
import kotlinx.coroutines.CoroutineScope
Set up the send function and the queue name:
val queueName = "hello"
suspend fun send(coroutineScope: CoroutineScope) {
// ...
}
Then we can create a connection to the server:
suspend fun send(coroutineScope: CoroutineScope) {
val config = amqpConfig {
server {
host = "localhost"
}
}
val connection = createAMQPConnection(coroutineScope, config)
val channel = connection.openChannel()
// Publishing code will go here...
channel.close()
connection.close()
}
The connection abstracts the socket connection, and takes care of protocol version negotiation and authentication and so on for us. Here we connect to a RabbitMQ node on the local machine - hence the localhost. If we wanted to connect to a node on a different machine we'd simply specify its hostname or IP address here.
Next we create a channel, which is where most of the API for getting things done resides.
To send, we must declare a queue for us to send to; then we can publish a message to the queue:
channel.queueDeclare(
queueName,
durable = false,
exclusive = false,
autoDelete = false,
arguments = emptyMap()
)
val message = "Hello World!"
channel.basicPublish(
message.toByteArray(),
exchange = "",
routingKey = queueName,
properties = Properties()
)
println(" [x] Sent '$message'")
Declaring a queue is idempotent - it will only be created if it doesn't exist already. The message content is a byte array, so you can encode whatever you like there.
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.
Setting up is the same as the publisher; we open a connection and a
channel, and declare the queue from which we're going to consume.
Note this matches up with the queue that send publishes to.
suspend fun receive(coroutineScope: CoroutineScope) {
val config = amqpConfig {
server {
host = "localhost"
}
}
val connection = createAMQPConnection(coroutineScope, config)
val channel = connection.openChannel()
channel.queueDeclare(
queueName,
durable = false,
exclusive = false,
autoDelete = false,
arguments = emptyMap()
)
println(" [*] Waiting for messages. To exit press CTRL+C")
// Consuming code will go here...
channel.close()
connection.close()
}
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.
We're about to tell the server to deliver us the messages from the queue. Since Kourier is built on Kotlin coroutines, consuming messages is as simple as iterating over a channel:
val consumer = channel.basicConsume(queueName, noAck = true)
for (delivery in consumer) {
val message = delivery.message.body.decodeToString()
println(" [x] Received '$message'")
}
Putting it all together
You can wrap both functions in a main function with a runBlocking block:
import dev.kourier.amqp.Properties
import dev.kourier.amqp.connection.amqpConfig
import dev.kourier.amqp.connection.createAMQPConnection
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
val queueName = "hello"
suspend fun send(coroutineScope: CoroutineScope) {
val config = amqpConfig {
server {
host = "localhost"
}
}
val connection = createAMQPConnection(coroutineScope, config)
val channel = connection.openChannel()
channel.queueDeclare(
queueName,
durable = false,
exclusive = false,
autoDelete = false,
arguments = emptyMap()
)
val message = "Hello World!"
channel.basicPublish(
message.toByteArray(),
exchange = "",
routingKey = queueName,
properties = Properties()
)
println(" [x] Sent '$message'")
channel.close()
connection.close()
}
suspend fun receive(coroutineScope: CoroutineScope) {
val config = amqpConfig {
server {
host = "localhost"
}
}
val connection = createAMQPConnection(coroutineScope, config)
val channel = connection.openChannel()
channel.queueDeclare(
queueName,
durable = false,
exclusive = false,
autoDelete = false,
arguments = emptyMap()
)
println(" [*] Waiting for messages. To exit press CTRL+C")
val consumer = channel.basicConsume(queueName, noAck = true)
for (delivery in consumer) {
val message = delivery.message.body.decodeToString()
println(" [x] Received '$message'")
}
channel.close()
connection.close()
}
fun main() = runBlocking {
launch { send(this) }
launch { receive(this) }
delay(Long.MAX_VALUE) // Keep the main thread alive
}
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).
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.