How
to install and configure RabbitMQ server on Ubuntu 16.04
Installation
and Configuration:
To
install RabbitMQ server on Ubuntu we need two debian packages.
1.
esl-erlang_20.1-1~ubuntu~xenial_amd64.deb
2.
rabbitmq-server_3.6.14-1_all.deb
These
debian packages can be downloaded from link,
Now
follow below steps to install.
apt-get
update
apt-get
upgrade
apt-get
-f install (if required)
dpkg
-i esl-erlang_20.1-1~ubuntu~xenial_amd64.deb
dpkg
-i rabbitmq-server_3.6.14-1_all.deb
Check
rabbitmq server is running with below command
service
rabbitmq-server status
Now,
we need to create user password in RabbitMQ server to access it.
Follow these commands to add new user and to give permissions.
rabbitmqctl
add_user username yourpassword
rabbitmqctl
set_user_tags username administrator
rabbitmqctl
set_permissions -p / username ".*" ".*" ".*"
RabbitMQ
server running on port 5672, so make sure this port is open on
machine in which RabbitMQ is installed.
Use
RabbitMQ with PHP
We
will use
php-amqplib client library, to setup it follow steps
below:
cd
/var/www/html ;(Goto any
folder where you want to create project folder)
mkdir
projectname
cd
projectname
php
-r "copy('https://getcomposer.org/installer',
'composer-setup.php');"
php
-r "if (hash_file('SHA384', 'composer-setup.php') ===
'544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061')
{ echo 'Installer verified'; } else { echo 'Installer corrupt';
unlink('composer-setup.php'); } echo PHP_EOL;"
php
composer-setup.php
php
-r "unlink('composer-setup.php');"
create
file, nano composer.json and add below content in it.
{
"require": {
"php-amqplib/php-amqplib": ">=2.6.1"
}
}
php
composer.phar install
Now
vendor folder will be created, inside autoload.php file will be there
which we will use.
Sample
Codes:
a)
send message
<?php
require_once
'vendor/autoload.php';
use
PhpAmqpLib\Connection\AMQPStreamConnection;
use
PhpAmqpLib\Message\AMQPMessage;
$connection
= new AMQPStreamConnection('localhost', 5672, 'yourusername',
'yourpassword');
$channel
= $connection->channel();
$channel->queue_declare('hello',
false, false, false, false);
$msg
= new AMQPMessage('Hello World!');
$channel->basic_publish($msg,
'', 'hello');
echo
" [x] Sent 'Hello World!'\n";
$channel->close();
$connection->close();
?>
b)
receive message
<?php
require_once
'vendor/autoload.php';
use
PhpAmqpLib\Connection\AMQPStreamConnection;
$connection
= new AMQPStreamConnection('localhost', 5672, 'yourusername',
'yourpassword');
$channel
= $connection->channel();
$channel->queue_declare('hello',
false, false, false, false);
echo
' [*] Waiting for messages. To exit press CTRL+C', "\n";
$callback
= function($msg) {
echo
" [x] Received ", $msg->body, "\n";
};
$channel->basic_consume('hello',
'', false, true, false, false, $callback);
while(count($channel->callbacks))
{
$channel->wait();
}
$channel->close();
$connection->close();
?>