RabbitMQ is the message broker. We can use that to schedule background tasks or send events asynchronously. There are good writeups on the benefits it gives to you: Top 10 Uses For A Message Queue, Main features and benefits of message queuing.

In this blogpost I am going to show how to use RabbitMQ to schedule some background tasks in PHP.

All examples are based on Enqueue PHP Messaging library.

Let’s suppose we have to process an uploaded image, apply some filters, crop, optimize the size and so on. Obviously these kind of tasks are good candidates for the background job. Once a user uploads a new image to the server it will send the message via RabbitMQ to the consumer to process the image.

To begin with we have to install RabbitMQ itself and the PHP client Enqueue Amqp library.

We are going to use Composer, if you don’t have Composer installed in your computer, start by installing Composer globally.

To install the library simply run the command:

$ composer require enqueue/amqp-ext

You could also install enqueue/amqp-lib or enqueue/amqp-bunny. Change namespaces accordingly.

The next step is to connect to RabbitMQ broker

If you run the script and there are no errors than we successfully establish the connection with the broker.

I assume that RabbitMQ broker is installed on localhost

The web process, once the image has been uploaded, has to send the message. To keep things simple let’s send the image path to the queue.

That was easy to send a message, isn’t it?. Let’s look how to consume the message and process it. We have to connect to the broker again, the code looks exactly the same as above. We have to create a consumer for our process_image queue and ask for the new message by calling the receive method. It can consume messages in a loop:

That’s basically it and we could end the story here. Though I’d like to show you how the consumption script could be improved. We are going to create a console command based on symfony/console component. Let’s install the component first:

$ composer require symfony/console:^3.2

And create a console app:

If you run php consume.php command it starts consuming messages from process_image queue. It has a handy stuff like usefull options, verbose logging and built it support of extensions (run php consume.php --help to find out more).

Here’s a short example that shows how easy to extend queue consumer with extra process signals support.

Conclusion

As you can see it is super easy to send messages to the queue and consume messages from it. These scripts work not only for RabbitMQ but for any other transports that are built on the top of Enqueue Message Service (a port of Java Message Service spec).

You can also visit our corporate blog to learn more about up-to-date IT trends and download some useful insights.