RabbitMQ : PHP から利用する2025/12/15 |
|
RabbitMQ を PHP から利用する例です。 |
|
| [1] | 事前に必要なパッケージをインストールしておきます。 |
|
dlp:~ # zypper -n install php8-pecl php8-devel librabbitmq-devel make dlp:~ # pecl install amqp dlp:~ # echo 'extension=amqp.so' >> /etc/php8/cli/php.ini
|
| [2] | PHP スクリプトからのメッセージ送信例です。 例として、[localhost] で稼働する RabbitMQ サーバーに、RabbitMQ ユーザー [serverworld] , バーチャルホスト [my_vhost] へ接続して利用します。 |
|
suse@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] | PHP スクリプトからのメッセージ受信例です。 例として、上記 [2] で送信したメッセージを受信します。 |
|
suse@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! |
| Sponsored Link |
|
|