RabbitMQ : Use on PHP |
This is an example to use RabbitMQ on PHP. | |
| [1] | Install some packages. |
# install from EPEL [root@dlp ~]# dnf --enablerepo=epel -y install php-pecl-amqp |
| [2] | This is an example of sending message on PHP. For example, connect with RabbitMQ on [localhost] with a user [serverworld], virtualhost [my_vhost]. |
[cent@dlp ~]$ vi send_msg.php <?php
$connection = new AMQPConnection();
$connection->setHost('127.0.0.1');
$connection->setVhost('/my_vhost');
$connection->setLogin('serverworld');
$connection->setPassword('password');
$connection->connect();
$channel = new AMQPChannel($connection);
$exchange = new AMQPExchange($channel);
try {
$routing_key = 'Hello_World';
$queue = new AMQPQueue($channel);
$queue->setName($routing_key);
$queue->setFlags(AMQP_NOPARAM);
$queue->declareQueue();
$message = 'Hello RabbitMQ World!';
$exchange->publish($message, $routing_key);
echo " [x] Sent 'Hello_World'\n";
$connection->disconnect();
}
catch (Exception $ex) {
print_r($ex);
}
?>
php send_msg.php [x] Sent 'Hello_World' |
| [3] | This is an example of receiving message on PHP. |
[cent@node01 ~]$ vi receive_msg.php <?php
$connection = new AMQPConnection();
$connection->setHost('10.0.0.30');
$connection->setVhost('/my_vhost');
$connection->setLogin('serverworld');
$connection->setPassword('password');
$connection->connect();
$channel = new AMQPChannel($connection);
$exchange = new AMQPExchange($channel);
$callback_func = function(AMQPEnvelope $message, AMQPQueue $q) use (&$max_consume) {
echo " [x] Received ", $message->getBody(), PHP_EOL;
$q->nack($message->getDeliveryTag());
sleep(1);
};
try {
$routing_key = 'Hello_World';
$queue = new AMQPQueue($channel);
$queue->setName($routing_key);
$queue->setFlags(AMQP_NOPARAM);
$queue->declareQueue();
echo ' [*] Waiting for messages. To exit press CTRL+C ', PHP_EOL;
$queue->consume($callback_func);
}
catch(AMQPQueueException $ex) {
print_r($ex);
}
catch(Exception $ex){
print_r($ex);
}
echo 'Close connection...', PHP_EOL;
$queue->cancel();
$connection->disconnect();
?>
php receive_msg.php [*] Waiting for messages. To exit press CTRL+C [x] Received Hello RabbitMQ World! |
No comments:
Post a Comment