note 109024 deleted from amqp.examples by sobak

From: Date: Thu, 24 Nov 2016 20:35:02 +0000
Subject: note 109024 deleted from amqp.examples by sobak
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-207594@lists.php.net to get a copy of this message
Note Submitter: jean dot weisbuch at phpnet dot org ---- The official documentation is not up to date as of June 2012 for the latest stable version (1.0.3) so i had to find semi-blindly how i could use the extension (thanks to some snippets on User Contributed Notes). Here is a simple way to publish and retrieve messages (tested using RabbitMQ as the broker) that works on the stable version of the extension : <?php function amqp_connection() { $amqpConnection = new AMQPConnection(); $amqpConnection->setLogin("username"); $amqpConnection->setPassword("123456"); $amqpConnection->setVhost("virthost"); $amqpConnection->connect(); if(!$amqpConnection->isConnected()) { die("Cannot connect to the broker, exiting !\n"); } return $amqpConnection; } function amqp_receive($exchangeName, $routingKey, $queueName) { $amqpConnection = amqp_connection(); $channel = new AMQPChannel($amqpConnection); $queue = new AMQPQueue($channel); $queue->setName($queueName); $queue->bind($exchangeName, $routingKey); while($message = $queue->get()) { echo("Message #".$message->getDeliveryTag()." '".$message->getBody()."'"); if($message->isRedelivery()) { echo("\t(this message has already been delivered)"); } // just for testing purpose, shows how to manually remove a message from queue if(rand(0,6) > 4) { $queue->ack($message->getDeliveryTag()); echo("\t(this message has been removed from the queue)"); } print_r($message->getMessageId()); echo "\n"; } if(!$amqpConnection->disconnect()) { throw new Exception("Could not disconnect !"); } } function amqp_send($text, $routingKey, $exchangeName){ $amqpConnection = amqp_connection(); $channel = new AMQPChannel($amqpConnection); $exchange = new AMQPExchange($channel); $exchange->setName($exchangeName); $exchange->setType("fanout"); $message = $exchange->publish($text, $routingKey); if(!$message) { echo "Error: Message '".$message."' was not sent.\n"; } else { echo "Message '".$message."' sent.\n"; } if (!$amqpConnection->disconnect()) { throw new Exception("Could not disconnect !"); } } // lets send a message with a "random" content (the date) amqp_send("Message added at this date: ".date(DATE_RFC822), "action", "amq.fanout"); // you need to sleep for 1 sec if you want to be able to receive the message you just sent ("limitation" must be on the broker side) sleep(1); // now we receive messages from the queue we just sent a message on amqp_receive("amq.fanout","action","action"); ?> The rand() part of the script is used to make it more "lively" for testing when the script is run many times by randomly acknowledging messages (and show how to acknowledge non-automatically a message after it has been read).

« previous php.notes (#207594) next »