/** * Execute the console command. * * @return mixed */ public function handle() { // $queue = 'cloudstack'; $conn = new AMQPStreamConnection(Config::get('rabbitmq.host'), Config::get('rabbitmq.port'), Config::get('rabbitmq.user'), Config::get('rabbitmq.pass'), Config::get('rabbitmq.vhost')); $channel = $conn->channel(); while ($message = $channel->basic_get($queue)) { $messageData = json_decode($message->body); // Don't think we care about messages that have no status or event if (empty($messageData->status) || empty($messageData->event)) { $channel->basic_ack($message->delivery_info['delivery_tag']); continue; } // For the moment, we don't care about non-Completed messages. if (!in_array($messageData->status, ['Completed', 'Created'])) { $channel->basic_ack($message->delivery_info['delivery_tag']); continue; } if (in_array($messageData->event, ['SNAPSHOT.CREATE', 'SNAPSHOT.DELETE', 'VM.CREATE', 'VM.DESTROY'])) { $messageHandled = $this->parseMessage($messageData); } else { $messageHandled = true; } if ($messageHandled == true) { $channel->basic_ack($message->delivery_info['delivery_tag']); } } $channel->close(); $conn->close(); }
/** * */ public function __destruct() { if ($this->connection) { $this->channel->close(); $this->connection->close(); } }
public function tearDown() { if ($this->ch) { $this->ch->exchange_delete($this->exchange_name); $this->ch->close(); } if ($this->conn) { $this->conn->close(); } }
/** * @Route("/register", name="security_register") * @Method("POST") */ public function registerAction(Request $request) { $em = $this->getDoctrine()->getManager(); $request = Request::createFromGlobals(); $email = $request->request->get('email'); $password = $request->request->get('password'); $ico = trim($request->request->get('ico')); $user = new User(); $encoder = $this->container->get('security.encoder_factory')->getEncoder($user); $user->setPassword($encoder->encodePassword($password, $user->getSalt())); $user->setEmail($email); $user->setIco($ico); $backgroundImages = ['animal', 'corn', 'farming', 'chicken']; shuffle($backgroundImages); $user->setBackgroundImage($backgroundImages[0]); $profileImages = ['animal', 'corn', 'farming', 'chicken']; shuffle($profileImages); $user->setProfileImage($profileImages[0]); $em->persist($user); $em->flush(); $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles()); $this->get('security.token_storage')->setToken($token); //rabbit MQ $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare('ico_queue', false, false, false, false); $json = json_encode(["userId" => $user->getId(), "ico" => $ico]); $msg = new AMQPMessage($json); $channel->basic_publish($msg, '', 'ico_queue'); dump(" [x] Sent '{$ico}'\n"); $channel->close(); $connection->close(); return $this->redirect($this->generateUrl('main_overview')); }
/** * Send an activity notice using AMQP * @param ActivityNotice $notice * @return bool */ public function sendActivityNotice($notice) { if (!isset($notice)) { return false; } /** @var array $setting */ $setting = $this->params['amqpSetting']; try { if ($this->amqpClientLibrary == "PhpAmqpLib") { $connection = new AMQPStreamConnection($setting['host'], $setting['port'], $setting['user'], $setting['password']); $channel = $connection->channel(); $msg = new AMQPMessage(JsonHelper::encode($notice)); $channel->basic_publish($msg, $setting['exchangeName'], $setting['routingKey']); $channel->close(); $connection->close(); } elseif ($this->amqpClientLibrary == "PECL") { $connection = new \AMQPConnection(['host' => $setting['host'], 'port' => $setting['port'], 'login' => $setting['user'], 'password' => $setting['password']]); $connection->connect(); if ($connection->isConnected()) { $channel = new \AMQPChannel($connection); $exchange = new \AMQPExchange($channel); $exchange->setName($setting['exchangeName']); $exchange->publish(JsonHelper::encode($notice), $setting['routingKey']); $connection->disconnect(); } } else { return false; } } catch (\Exception $e) { return false; } return true; }
/** * Disconnects from the message broker */ public function disconnect() { if ($this->connection !== null) { $this->channel->close(); $this->connection->close(); } return $this; }
/** * Closing connection to the server with possible to delete queue * @param bool|false $delete Set true for delete queue before closing connection */ public function close($delete = false) { if ($delete) { $this->delete(); } $this->channel->close(); $this->connection->close(); }
function forward_to_router($msg, $routing_key) { $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare($routing_key, false, false, false, false); $channel->basic_publish($msg, '', $routing_key); $channel->close(); $connection->close(); }
/** * Close the channel and connections to AMQP * * @return void */ public function closeConnections() { if ($this->channel) { $this->channel->close(); } if ($this->connection) { $this->connection->close(); } }
/** * @return void */ public function closeConnection() { $this->closeChannel(); if ($this->connection instanceof AbstractConnection) { $this->connection->close(); $this->logger->info('Connection clossed!', ['server' => $this->server, 'port' => $this->port, 'vhost' => $this->vhost]); } $this->connection = null; }
function forward_to_translator($msg, $routing_key) { $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->exchange_declare('bank_translators_exchange', 'direct', false, false, false); $channel->basic_publish($msg, 'bank_translators_exchange', $routing_key); $channel->close(); $connection->close(); }
public function __destruct() { $this->channel->close(); unset($this->channel); $this->connection->close(); unset($this->connection); unset($this->replyQueueName); unset($this->consumerTag); unset($this->outputMessages); }
public function sendBuyServiceToRabbit($taskId, $resourceId) { $connection = new AMQPStreamConnection(RABBIT_URL, RABBIT_PORT, RABBIT_USER, RABBIT_PASSWORD); $channel = $connection->channel(); $channel->queue_declare($taskId, false, false, false, false); $msg = new AMQPMessage($resourceId); $channel->basic_publish($msg, '', $taskId); $channel->close(); $connection->close(); }
/** * Closes the transient connection with the AMQP broker. * * This method will close an open connection with the AMQP broker. * * @return boolean true if connection was successfully closed, false otherwise. */ public function disconnect() { if (!$this->isConnected()) { return false; } try { $this->connection->close(); } catch (Exception $e) { return false; } return true; }
public function subscribe() { $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare('aggregator', false, false, false, false); $channel->basic_consume('aggregator', '', false, true, false, false, array($this, 'on_response')); echo ' [*] Waiting for messages. To exit press CTRL+C', "\n"; while (count($channel->callbacks)) { $channel->wait(); } $channel->close(); $connection->close(); }
protected function setUp() { // drop AMQP server state $amqpConnection = new AMQPStreamConnection(TASK_QUEUE_AMQP_HOST, TASK_QUEUE_AMQP_PORT, TASK_QUEUE_AMQP_USER, TASK_QUEUE_AMQP_PASSWORD); $channel = $amqpConnection->channel(); $channel->queue_delete(TASK_QUEUE_AMQP_QUEUE_NAME); $channel->close(); $amqpConnection->close(); $channel = null; $amqpConnection = null; $this->mockApplication($this->getAppConfig()); parent::setUp(); }
/** * Отключаемся * * @return bool */ protected function _disconnect() { try { if ($this->_connected) { $this->_Channel->close(); $this->_Connection->close(); } } catch (\Exception $e) { } $this->_Channel = $this->_Connection = null; $this->_connected = false; return !$this->_connected; }
/** * @param callable $callback */ public function connect(callable $callback) { printf(" %s host %s port %s channel %s\n", __METHOD__, $this->host, $this->port, $this->channel_name); $connection = new AMQPStreamConnection($this->host, $this->port, 'guest', 'guest'); $channel = $connection->channel(); $channel->exchange_declare($this->channel_name, 'fanout', false, false, false); list($queue_name, , ) = $channel->queue_declare("", false, false, true, false); $channel->queue_bind($queue_name, $this->channel_name); $channel->basic_consume($queue_name, '', false, true, false, false, $callback); while (count($channel->callbacks)) { $channel->wait(); } $channel->close(); $connection->close(); }
protected function execute(InputInterface $input, OutputInterface $output) { if ($input->getOption('ssl')) { $output->writeln('SSL Enabled'); $connection = new AMQPSSLConnection($input->getOption('host'), $input->getOption('port'), $input->getOption('username'), $input->getOption('password'), '/', array('allow_self_signed' => false)); } else { $output->writeln('SSL Disabled'); $connection = new AMQPStreamConnection($input->getOption('host'), $input->getOption('port'), $input->getOption('username'), $input->getOption('password')); } $channel = $connection->channel(); $message = new AMQPMessage($input->getOption('message'), array('content_type' => 'text/plain', 'delivery_mode' => 2)); $channel->basic_publish($message, $input->getOption('exchange')); $channel->close(); $connection->close(); }
public function postPosition($idPath, $latitude, $longitude, $at) { global $logger; global $db; if (!$db->getFromTableWhere('path', ['id' => $idPath])) { $logger->log('warning', 'Request API POST Position - No path with id ' . $idPath . ' find in database'); return $this->autoHttpCode(false); } $timestamp = new \DateTime(); $timestamp->setTimestamp($at); $logger->log('info', 'Request API PUT Status with path id : ' . $idPath . ', latitude : ' . $latitude . ', longitude : ' . $longitude . ' at ' . $timestamp->format('Y-m-d G:i:s')); $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare('post_position', false, true, false, false); $data = array('path_id' => $idPath, 'latitude' => $latitude, 'longitude' => $longitude, 'at' => $timestamp->format('Y-m-d G:i:s')); $msg = new AMQPMessage(json_encode($data), array('delivery_mode' => 2)); $channel->basic_publish($msg, '', 'post_position'); $channel->close(); $connection->close(); return $this->autoHttpCode(); }
/** * Cette fonction permet d'appeler la vérification des interventions des reparateurs */ public function checkInterventionResponse() { global $logger; global $db; for ($i = 0; $i < 30; $i++) { $logger->log('info', 'Script check intervention response'); if (!($interventions = $db->getFromTableWhere('intervention', ['status' => internalConstants::$interventionStatus['WAIT']]))) { return false; } $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare('check_intervention', false, true, false, false); foreach ($interventions as $intervention) { $msg = new AMQPMessage(json_encode($intervention), ['delivery_mode' => 2]); $channel->basic_publish($msg, '', 'check_intervention'); } $channel->close(); $connection->close(); sleep(2); } }
protected function execute(InputInterface $input, OutputInterface $output) { // Connection a RabbitMQ $connection = new AMQPStreamConnection('rabbitmq', 5672, 'guest', 'guest'); $channel = $connection->channel(); // Déclaration de la queue $channel->queue_declare($queue = 'tasks', $passive = false, $durable = true, $exclusive = false, $auto_delete = false); // Préparation des datas $data = ['class' => 'RabbitmqTest\\Object', 'id' => rand(1, 100), 'methode' => 'genCacheMembers']; // On json le tout $json = json_encode($data); // On Envoi le message dans la queu tasks $msg = new AMQPMessage($json, ['delivery_mode' => 2]); $channel->basic_publish($msg, '', 'tasks'); // Infos $output->writeln("<comment>#################################################</comment>"); $output->writeln("<comment>Envoi du json : </comment>"); $output->writeln("<info>" . json_encode($data, JSON_PRETTY_PRINT) . "</info>"); $output->writeln("<comment>#################################################</comment>"); // On ferme tous $channel->close(); $connection->close(); }
/** * @param $name * @param $config * @param int $level * @return LoggerInterface * @throws \Exception */ public static function createLogger($name, $config = [], $level = \Monolog\Logger::DEBUG) { if (!isset(self::$loggers[$name])) { if (!empty($config) && isset($config[self::LOGGER_LEVEL])) { $level = $config[self::LOGGER_LEVEL]; } $logger = new \Monolog\Logger($name); $logger->pushHandler(new StreamHandler('php://stdout')); $file = PATH_ROOT . '/logs/' . preg_replace('/[\\/\\\\._-]+/', ".", $name) . ".log"; $logger->pushHandler(new StreamHandler($file, $level, true, 0766)); if (!empty($config) && (isset($config['amqp']) || isset($config['vhost']))) { $host = isset($config['amqp']) ? $config['amqp']['host'] : $config['host']; $port = isset($config['amqp']) ? $config['amqp']['port'] : $config['port']; $user = isset($config['amqp']) ? $config['amqp']['user'] : $config['user']; $password = isset($config['amqp']) ? $config['amqp']['password'] : $config['password']; $vhost = isset($config['amqp']) ? $config['amqp']['vhost'] : $config['vhost']; $channel = null; try { $conn = new AMQPStreamConnection($host, $port, $user, $password, $vhost); $channel = $conn->channel(); $channel->exchange_declare('monitor-log', 'topic', false, true, false); register_shutdown_function(function () use($conn, $channel) { $channel->close(); $conn->close(); }); } catch (\Exception $e) { // throw $e; // echo 'amqp logger error: ' . $e->getMessage() . "\n" . $e->getTraceAsString(); } if ($channel !== null) { $logger->pushHandler(new AmqpHandler($channel, 'monitor-log', $level)); } } self::$loggers[$name] = $logger; } return self::$loggers[$name]; }
/** * Cette fonction prend une intervention qui n'a pas reçue de réponse et vérifie si elle doit être annulée */ public function checkIntervention() { $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare('check_intervention', false, true, false, false); $callback = function ($msg) { global $logger; global $db; $logger->log('info', 'Worker - Check intervention'); $intervention = json_decode($msg->body, true); $limit = new DateTime(); $limit->sub(new DateInterval('PT5M')); $interventionStartDate = new DateTime($intervention['start_date']); //Si ça fait moins de 5 minutes qu'on à lancé la demande d'intervention if ($limit < $interventionStartDate) { $logger->log('info', 'Worker - ask intervention for less than 5 minutes for intervention with id : ' . $intervention['id']); $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']); } else { $logger->log('info', 'Worker - intervention with id . ' . $intervention['id'] . ' is refused'); $newStatus = internalConstants::$interventionStatus['REFUSED']; $newEndDate = new DateTime(); $newEndDate = $newEndDate->format('Y-m-d H:i:s'); $db->updateTableWhere('intervention', ['status' => $newStatus, 'end_date' => $newEndDate], ['id' => $intervention['id']]); $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']); } }; $channel->basic_qos(null, 1, null); $channel->basic_consume('check_intervention', '', false, false, false, false, $callback); while (count($channel->callbacks)) { $channel->wait(); } $channel->close(); $connection->close(); }
/** * @param AMQPChannel $channel * @param AMQPStreamConnection $connection */ public static function shutdown(AMQPChannel $channel, AMQPStreamConnection $connection) { $channel->close(); $connection->close(); }
/** * Disconnect amqp connection */ public function disconnect() { $this->channel->close(); $this->amqpConnection->close(); }
echo ' value="' . htmlspecialchars($_POST['domain']) . '"'; } ?> /></div> <div class="col-xs-6 col-xs-offset-3 col-sm-2 col-sm-offset-0"><button type="submit" class="btn btn-default">Go <i class="fa fa-caret-right"></i></button></div> </div> </form> </div> <?php } else { $conn = new AMQPStreamConnection("127.0.0.1", "5672", "guest", "guest", "/"); $ch = $conn->channel(); $ch->set_ack_handler(function (AMQPMessage $message) { echo "Message acked with content " . $message->body . PHP_EOL; }); $ch->set_nack_handler(function (AMQPMessage $message) { echo "Message nacked with content " . $message->body . PHP_EOL; }); $ch->confirm_select(); $ch->queue_declare('domains', false, true, false, false); $ch->basic_publish(new AMQPMessage($_POST["domain"], array('delivery_mode' => 2)), '', 'domains'); $ch->wait_for_pending_acks_returns(); $ch->close(); $conn->close(); } ?> </div> </body> </script> </html>
use PhpAmqpLib\Connection\AMQPStreamConnection; use PhpAmqpLib\Message\AMQPMessage; $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare('rpc_queue', false, false, false, false); function fib($n) { if ($n == 0) { return 0; } if ($n == 1) { return 1; } return fib($n - 1) + fib($n - 2); } echo " [x] Awaiting RPC requests\n"; $callback = function ($req) { $n = intval($req->body); echo " [.] fib(", $n, ")\n"; $msg = new AMQPMessage((string) fib($n), array('correlation_id' => $req->get('correlation_id'))); $req->delivery_info['channel']->basic_publish($msg, '', $req->get('reply_to')); $req->delivery_info['channel']->basic_ack($req->delivery_info['delivery_tag']); }; $channel->basic_qos(null, 1, null); $channel->basic_consume('rpc_queue', '', false, false, false, false, $callback); while (count($channel->callbacks)) { $channel->wait(); } $channel->close(); $connection->close();
/** * Close channel and connection */ public function close() { $this->channel && $this->channel->close(); $this->connection->close(); }
function forward_to_normalizer($response) { $connection = new AMQPStreamConnection('localhost', 5672, 'test', 'test'); $channel = $connection->channel(); $channel->queue_declare("bank_normalizer", false, false, true, false); $msg = new AMQPMessage($response); $channel->basic_publish($msg, '', 'bank_normalizer'); $channel->close(); $connection->close(); }