Skip to content

Instantly share code, notes, and snippets.

@sokil
Last active August 29, 2015 14:05
Show Gist options
  • Save sokil/89b71dac442e3da03c3c to your computer and use it in GitHub Desktop.
Save sokil/89b71dac442e3da03c3c to your computer and use it in GitHub Desktop.
RabbitMQ Producer-Consumer (https://github.com/videlalvaro/php-amqplib)
<?php
use PhpAmqpLib\Connection\AMQPConnection;
use PhpAmqpLib\Message\AMQPMessage;
// connect
$connection = new AMQPConnection('localhost', 5672, 'guest', 'guest');
// create channel
$channel = $connection->channel();
$channel->queue_declare('flowers', false, true);
// assign job to consumer only if consumer done previous job and it confirmed
$channel->basic_qos(null, 1, null);
// redister callback
$channel->basic_consume('flowers', '', false, false, false, false, function(AMQPMessage $msg) {
// print message
echo 'Received: ' . $msg->body . PHP_EOL;
/* @var $channel \PhpAmqpLib\Channel\AMQPChannel */
$channel = $msg->delivery_info['channel'];
$deliveryTag = $msg->delivery_info['delivery_tag'];
echo 'Delivery tag: ' . $deliveryTag . PHP_EOL . PHP_EOL;
$channel->basic_ack($deliveryTag);
});
// start loop
echo 'Start loop' . PHP_EOL;
while(count($channel->callbacks)) {
$channel->wait();
}
<?php
use PhpAmqpLib\Connection\AMQPConnection;
use PhpAmqpLib\Message\AMQPMessage;
// connect
$connection = new AMQPConnection('localhost', 5672, 'guest', 'guest');
// create channel
$channel = $connection->channel();
$channel->queue_declare('flowers', false, true);
// send message
$message = new AMQPMessage('say hello at ' . date('Y-m-d H:i:s'), array(
'delivery_mode' => 2,
));
$channel->basic_publish($message, '', 'flowers');
// close
$channel->close();
$connection->close();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment