RabbitMQ, Implementation of RabbitMQ in YII.

What is RabbitMQ?

RabbitMQ is open source software used to manage the queue. We can queue our application tasks to execute them in async way by using RabbitMQ. In simple word it is a software where queue can be defined then message can be passed on these queue and different applications may connect to queue to process those message. Message can have any kind of data, it could be a simple text message or any action driven data.

Why we need RabbitMQ in our Project?

In our recent project we need to do many tasks on a event completion. Firstly we were doing it in sync way, it was taking 8-10 seconds. Due to that user have to wait till all these tasks complete. So to improve user experience we need to functionality where we can do all these tasks in async manner. So we studied many blogs and post and we came to know about pthreading and event-observer pattern. But these were not fulfilling our requirement because p threading is not good for web server environment and event observer was not making it async in a best manner. So finally we studied about queue and find RabbitMQ better for our requirements.  

Architecture of RabbitMQ

The bais architecture of rabbitMQ is simple, client applications that create and publish/deliver message to queue are called producers (message queue). Other applications that connects to the queue and subscribes to the messages and process called consumers. So RabbitMQ works on a producer consumer paradigm. Messages delivered onto the queue are stored until the consumer retrieves them and acknowledge queue.

Install RabbitMQ


  • To start, stop, restart and check the application status, use the following:

    Implementation in Project

    Here we will discuss how we can implement RabbitMQ in YII.

    Step 1 : Add this line in your composer.json and run composer update.

    Step 2 : Now we need to configure it. For this add following configuration setting in common/config/main-local.php

    Step 3 : How to create and deliver message on queue

    • Add these line on top of your file to include

    • Use following code in your function to deliver message on queue

     

    Step 4: Subscribe to queue and retrieves message.

    Enable RabbitMQ Management Console

    Once you’ve enabled the console, it can be accessed using your favourite web browser by visiting: http://127.0.0.1:15672/

    Other Useful Commands

    You can check what RabbitMQ queues has and how many messages are in them. You can check it using the rabbitmqctl tool:

    Thanks for reading.

    In our next chapter we will discuss in details about Exchanges, Queues, Binding and Routing Key and how we can make our exchange/queue persistent.