note 104117 deleted from amqp.examples by sobak

From: Date: Thu, 24 Nov 2016 20:34:38 +0000
Subject: note 104117 deleted from amqp.examples by sobak
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-207586@lists.php.net to get a copy of this message
Note Submitter: kurt at surfmerchants dot com ---- The docs for this extension are a little vague, so I'm adding a few things I found helpful in getting this to work. Helpful reading: * http://en.wikipedia.org/wiki/AMQP * http://www.rabbitmq.com/getstarted.html Helpful tool: /usr/sbin/rabbitmqctl list_queues Here I've split the usage example into a sender and receiver, because that is much more useful (at least to me): send.php : #!/usr/bin/php -q <?php // config $exchangeName = 'myexchange'; $routingKey = 'routing.key'; $message = $argv[1]; // connect $connection = new AMQPConnection(); $connection->connect(); // setup exchange $ex = new AMQPExchange($connection); $ex->declare($exchangeName, AMQP_EX_TYPE_FANOUT); // Publish a message to the exchange with our routing key $ex->publish($message, $routingKey); // disconnect $connection->disconnect(); ?> receive.php: #!/usr/bin/php -q <?php // config $exchangeName = 'myexchange'; $routingKey = 'routing.key'; $queueName = 'myqueue'; // connect $connection = new AMQPConnection(); $connection->connect(); // setup our queue $q = new AMQPQueue($connection); $q->declare($queueName); // Bind it on the exchange to routing.key $q->bind($exchangeName, $routingKey); // show the message print_r($q->get()); // disconnect $connection->disconnect(); ?> The first time you run "./send.php 'hello world'", then "./receive.php", you will not get the message, because the receiver creates the queue. That's OK. While you *can* create the queue in the sender, this is not so useful, because it's really the receivers that read the queue, and I've found that various clients are very picky about the details of how the queue was created (for example, if I create the queue in my php sender, then try to listen with a python receiver, it throws errors, but if I let the python receiver create the queue, all is well). So, the second time you send a message (after running receive.php once), the queue will exist, and you will then get the message the next time you run receive. Another thing I noticed is that I'm using $q->get() instead of $q->consume(), because the latter seems to segfault (at least on my CentOS 5.5 system).

« previous php.notes (#207586) next »