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 Objective-C Client)
In this part of the tutorial we'll write a simple iOS app. It will send a
single message, and consume that message and log it using print
.
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 Objective-C 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 Objective-C client in this tutorial.
Creating an Xcode project with the RabbitMQ client dependency
Follow the instructions below to create a new Xcode project.
- Create a new Xcode project with File -> New -> Project…
- Choose iOS Application -> Single View Application
- Click Next
- Give your project a name, e.g. "RabbitTutorial1".
- Fill in organization details as you wish.
- Choose Swift as the language. You won't need Unit Tests for the purpose of this tutorial.
- Click Next
- Choose a place to create the project and click Create
Now we must add the Objective-C client as a dependency. This is done partly from the command-line. For detailed instructions, visit the client's GitHub page.
Once the client is added as a dependency, build the project with Product -> Build to ensure that it is linked correctly.
Sending
To keep things easy for the tutorial, we'll put our send and receive code in the same view controller. The sending code will connect to RabbitMQ and send a single message.
Let's edit ViewController.swift and start adding code.
Importing the framework
First, we import the client framework as a module:
import RMQClient
Now we call some send and receive methods from viewDidLoad
:
override func viewDidLoad() {
super.viewDidLoad()
self.send()
self.receive()
}
The send method begins with a connection to the RabbitMQ broker:
func send() {
print("Attempting to connect to local RabbitMQ broker")
let conn = RMQConnection(delegate: RMQConnectionDelegateLogger())
conn.start()
}
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 broker on the local machine with all default settings. A logging delegate is used so we can see any errors in the Xcode console.
If we wanted to connect to a broker on a different
machine we'd simply specify its name or IP address using the initWithUri(delegate:)
convenience initializer:
let conn = RMQConnection(uri: "amqp://myrabbitserver.com:1234",
delegate: RMQConnectionDelegateLogger())
Next we create a channel, which is where most of the API for getting things done resides:
let ch = conn.createChannel()
To send, we must declare a queue for us to send to; then we can publish a message to the queue:
let q = ch.queue("hello")
ch.defaultExchange().publish("Hello World!".data(using: .utf8), routingKey: q.name)
Declaring a queue is idempotent - it will only be created if it doesn't exist already.
Lastly, we close the connection:
conn.close()
Here's the whole controller (including receive).
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 sending. Our receive
method will spin up a consumer that will
be pushed messages from RabbitMQ, so unlike send
which publishes a single
message, it will wait for a message, log it and then quit.
Setting up is the same as send
; 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.
func receive() {
print("Attempting to connect to local RabbitMQ broker")
let conn = RMQConnection(delegate: RMQConnectionDelegateLogger())
conn.start()
let ch = conn.createChannel()
let q = ch.queue("hello")
}
Note that we declare the queue here, as well. Because we might start the receiver before the sender, 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 it will push messages to us asynchronously, we provide a
callback that will be executed when RabbitMQ pushes messages to
our consumer. This is what RMQQueue subscribe()
does.
print("Waiting for messages.")
q.subscribe({(_ message: RMQMessage) -> Void in
print("Received \(String(data: message.body, encoding: .utf8))")
})
Here's the whole controller again (including send).
Running
Now we can run the app. Hit the big play button, or cmd-R
.
receive
will log the message it gets from send
via
RabbitMQ. The receiver will keep running, waiting for messages (Use the Stop
button to stop it), so you could try sending messages to the same queue using
another client.
If you want to check on the queue, try using rabbitmqctl list_queues
.
Hello World!
Time to move on to part 2 and build a simple work queue.