Ubuntu 24.04
Sponsored Link

RabbitMQ : PHP पर प्रयोग करें2024/07/22

 

यह PHP पर RabbitMQ का उपयोग करने का एक उदाहरण है।

[1] कुछ पैकेज स्थापित करें।
root@dlp:~#
apt -y install php-amqp
[2] यह PHP पर संदेश भेजने का एक उदाहरण है।
उदाहरण के लिए, एक उपयोगकर्ता [serverworld], वर्चुअलहोस्ट [my_vhost] के साथ [localhost] पर RabbitMQ से जुड़ें।
ubuntu@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);
}

?>

ubuntu@dlp:~$
php send_msg.php

 [x] Sent 'Hello_World'
[3] यह PHP पर संदेश प्राप्त करने का एक उदाहरण है।
ubuntu@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();

?>

ubuntu@node01:~$
php receive_msg.php

 [*] Waiting for messages. To exit press CTRL+C
 [x] Received Hello RabbitMQ World!
मिलान सामग्री