Skip to content

Instantly share code, notes, and snippets.

@manav148
Last active August 29, 2015 14:08
Show Gist options
  • Save manav148/d436073a1ef5e3990de6 to your computer and use it in GitHub Desktop.
Save manav148/d436073a1ef5e3990de6 to your computer and use it in GitHub Desktop.
RabbitMQ sample publisher
<?php
use PhpAmqpLib\Connection\AMQPConnection;
use PhpAmqpLib\Message\AMQPMessage;
class RabbitMQ{
private $AMQPConnection;
private $Channel;
private $queue_name;
function __construct( $queue_name ) {
$connection_attempts = 10;
global $RABBIT_CONNECTIONS ;
for( $i = 0 ; $i < $connection_attempts ; $i++ ) {
try {
$this->queue_name = $queue_name;
$RabbitServer = new RabbitServer();
// Loading Random Rabbit Server
$RabbitServer->loadRandomServerForAccepting();
// If there is a global connection object reuse it
if ( @$RABBIT_CONNECTIONS[ $RabbitServer->getIP() ] ) {
$this->AMQPConnection = @$RABBIT_CONNECTIONS[ $RabbitServer->getIP() ][ 'connection' ] ;
}
else {
// Fork a new connection
$this->AMQPConnection = @$RABBIT_CONNECTIONS[ $RabbitServer->getIP() ][ 'connection' ] =
new AMQPConnection( $RabbitServer->getIP() ,$RabbitServer->getPort() ,
$RabbitServer->getUser(),$RabbitServer->getPassword() , $RabbitServer->getVhost() );
}
// Create a new channel for connection
$this->Channel = $this->AMQPConnection->channel();
// Declare the queue
$this->Channel->queue_declare( $queue_name , false , true , false , false );
}
catch (Exception $e){
addToRabbitLog( "Hitting exception for Rabbit connection construct: ".$e->getMessage(),
'rabbit_connection' ) ;
}
}
}
function addToQueue( $object ) {
try{
$message = new AMQPMessage($object,array('content_type' => 'text/plain','delivery_mode' => 2));
$this->Channel->basic_publish($message,"",$this->queue_name);
}
catch (Exception $e){
addToRabbitLog( "Hitting exception for Rabbit add to queue: ".$e->getMessage() ,
'rabbit_connection' ) ;
}
}
}
<?php
$values = array();
// Testing multiple channels
for ($i=0; $i < 10; $i++) {
$time_start = microtime();
$RabbitMQC = new RabbitMQ("multiple_connections_test");
echo "TimePassed RabbitMQ : ".print_r($diff = (microtime() - $time_start)*1000,true)." ms \n";
if($diff > 0)
$values[]= $diff;
$RabbitMQC->addToQueue("lol");
}
echo "Average time : ".print_r(@array_sum($values)/count($values),true)."\n";
// Sample output:
// TimePassed RabbitMQ : 48.109 ms
// TimePassed RabbitMQ : 40.783 ms
// TimePassed RabbitMQ : 39.799 ms
// TimePassed RabbitMQ : 39.598 ms
// TimePassed RabbitMQ : 39.682 ms
// TimePassed RabbitMQ : 39.938 ms
// TimePassed RabbitMQ : 39.318 ms
// TimePassed RabbitMQ : 40.094 ms
// TimePassed RabbitMQ : 40.169 ms
// TimePassed RabbitMQ : -960.253 ms
// Average time : 40.832222222222 ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment