What’s RabbitMQ?
RabbitMQ is a queuing system which is based on queuing protocol called AMQP and mainly used for queuing jobs that’s initiated from a source which we call it a producer, then RabbitMQ manages these requests by putting them in a queue or several queues according to the configuration.
Then these messages are handled by destination which we call consumer.
The main advantage to RabbitMQ or other queuing systems that the decouple the application to different parts, so more control over scalability.
Also better handling for incoming jobs/tasks which maybe very huge number in small amount of time (ex: 100s per second or maybe more), better handling means that they will be distributed to the right queues, consumed by the right consumers and also guarantee that no tasks are stuck or dropped or maybe consumed 2 times by 2 different consumers, which may lead to errors in your application.
Installing RabbitMQ
RabbitMQ is similar to other software, it can be installed using yum/apt and can be installed in 1 minute.
I assume you’re installing on a new server, instead of apt you can use yum if you have centos/RHEL.
sudo apt update && upgrade
sudo apt install erlang
sudo apt install rabbitmq-server
systemctl enable rabbitmq-server
systemctl start rabbitmq-server
systemctl status rabbitmq-server
rabbitmq-plugins enable rabbitmq_management
- now the above commands installed Erlang as dependency, then RabbitMQ.
- enabling RabbitMQ.
- installing management plugin to use its GUI.
now we’ve installed it.
to login do the below.
localhost:15672
or
<http://IP:15672>
In the first command you will access the admin dashboard by using username and password “guest”
the second one will refuse because only localhost is allowed.
to login remotely we need to enable it in configuration, follow the code below.
cd /etc/rabbitmq/nano rabbitmq.conf
#Add the following line, then save and exit
loopback_users = none
#restart the servicesystemctl rabbitmq-server restart
Then login again and it’ll succeed.
we can now add a user that’s admin, follow the below to create a user and add all privileges to it.
rabbitmqctl add_user admin admin
rabbitmqctl set_user_tags admin administrator
rabbitmqctl set_permissions -p / admin "." "." "."
Now we’re logged in with our super admin
Now Let’s jump to the step of building producer.
Building a Producer
to build a producer, i prefer to use nodeJS due to its simplicity and also because i like JavaScript.
at first create a directory to build our project files in it.
and then follow the below commands to prepare the environment, and for npm commands please use it inside project directory
sudo apt install npm
curl -sL <https://deb.nodesource.com/setup_14.x> | sudo -E bash
sudo apt-get install -y nodejs
npm init -y
npm install amqplib
inside the directory we need to create 2 files, producer.js and consumer.js
The below code is a simple code for both producing and consuming your messages