CentOS Stream 8
Sponsored Link

RabbitMQ : PHP から利用する2021/06/21

 
RabbitMQ を PHP から利用する例です。
[1] 事前に必要なパッケージをインストールしておきます。
# RabbitMQ, PowerTools からインストール

[root@dlp ~]#
dnf --enablerepo=centos-rabbitmq-38,powertools -y install librabbitmq-devel php-pear php-devel zlib-devel make
[root@dlp ~]#
pecl install amqp

[root@dlp ~]#
echo 'extension=amqp.so' >> /etc/php.d/99-amqp.ini

[2] PHP スクリプトからのメッセージ送信例です。
例として、[localhost] で稼働する RabbitMQ サーバーに、RabbitMQ ユーザー [serverworld] , バーチャルホスト [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);
}

?>

[cent@dlp ~]$
php send_msg.php

 [x] Sent 'Hello_World'
[3] PHP スクリプトからのメッセージ受信例です。
例として、上記 [2] で送信したメッセージを受信します。
[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();

?>

[cent@node01 ~]$
php receive_msg.php

 [*] Waiting for messages. To exit press CTRL+C
 [x] Received Hello RabbitMQ World!
関連コンテンツ