[3] RabbitMQ – PHP
22 marca 2022To jest przykład użycia RabbitMQ w PHP.
[1] Zainstaluj kilka pakietów.
# zainstaluj z RabbitMQ, PowerTools [root@vlsr01 ~]# dnf --enablerepo=centos-rabbitmq-38,powertools install librabbitmq-devel php-pear php-devel zlib-devel make [root@vlsr01 ~]# pecl install amqp [root@vlsr01 ~]# echo 'extension=amqp.so' >> /etc/php.d/99-amqp.ini
[2] To jest przykład wysyłania wiadomości w PHP.
Na przykład połącz się z RabbitMQ na [localhost] z użytkownikiem [zicherlab], virtualhost [my_vhost].
[user01@vlsr01 ~]$ mcedit send_msg.php # stwórz nowy <?php $connection = new AMQPConnection(); $connection->setHost('127.0.0.1'); $connection->setVhost('/my_vhost'); $connection->setLogin('zicherlab'); $connection->setPassword('Z1ch3rka'); $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); } ?> [user01@vlsr01 ~]$ php send_msg.php [x] Sent 'Hello_World'
[3] Zainstaluj PHP na hoście odbiorcy – patrz tutaj.
[4] Zainstaluj kilka pakietów na hoście odbiorcy.
# zainstaluj z RabbitMQ, PowerTools [root@vlsr02 ~]# dnf --enablerepo=centos-rabbitmq-38,powertools install librabbitmq-devel php-pear php-devel zlib-devel make [root@vlsr02 ~]# pecl install amqp [root@vlsr02 ~]# echo 'extension=amqp.so' >> /etc/php.d/99-amqp.ini
[5] To jest przykład odbierania wiadomości w PHP.
[user01@vlsr02 ~]# mcedit receive_msg.php # stwórz nowy <?php $connection = new AMQPConnection(); $connection->setHost('192.168.100.101'); $connection->setVhost('/my_vhost'); $connection->setLogin('zicherlab'); $connection->setPassword('Z1ch3rka'); $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(); ?> [user01@vlsr02 ~]$ php recive_msg.php [*] Waiting for messages. To exit press CTRL+C [x] Received Hello RabbitMQ World! # jest OK, odebrano wiadomość wyslaną w [2]