/** * 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(); }
protected function execute(InputInterface $input, OutputInterface $output) { // Connection a RabbitMQ $connection = new AMQPStreamConnection('rabbitmq', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->basic_qos(null, 1, null); // On ne traite pas plus de 1 message à la fois // Déclaration de la queue $channel->queue_declare($queue = 'tasks', $passive = false, $durable = true, $exclusive = false, $auto_delete = false); $output->writeln("<fg=black;bg=cyan>####################################################</>"); $output->writeln("<fg=black;bg=cyan>#### Waiting for messages. To exit press CTRL+C ####</>"); $output->writeln("<fg=black;bg=cyan>####################################################</>"); $callback = function ($msg) use($output) { $output->writeln(""); $output->writeln("--------------------------"); $output->writeln("<comment>Data reçu : </comment>"); $task = json_decode($msg->body, true); $output->writeln("<info>" . json_encode($task, JSON_PRETTY_PRINT) . "</info>"); $output->writeln(""); $output->writeln("<comment>Build de l'objet " . $task['class'] . " avec l'id " . $task['id'] . "</comment>"); $object = new $task['class']($task['id']); $output->writeln("<comment>Execution de la méthode</comment>"); $object->{$task}['methode'](); $output->writeln(""); $output->writeln("<comment>Fin de l'execution de la méthode</comment>"); $output->writeln("<comment>Envoi a RabbitMQ que la message à était traité</comment>"); $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']); }; $channel->basic_consume($queue = 'tasks', $consumer_tag = '', $no_local = false, $no_ack = false, $exclusive = false, $nowait = false, $callback); while (count($channel->callbacks)) { $channel->wait(); } }
/** * 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; }
/** * @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')); }
protected function getChannel() { if (null === $this->channel) { $this->channel = $this->connection->channel(); } return $this->channel; }
/** * */ public function __destruct() { if ($this->connection) { $this->channel->close(); $this->connection->close(); } }
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(); }
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(); }
/** * @param $exchange_name */ private function connect($exchange_name) { if (null !== $this->channel) { return; } $this->channel = $this->connection->channel(); $this->channel->exchange_declare($exchange_name, 'fanout', false, true, false); $this->channel->queue_declare($exchange_name, false, true, false, false); $this->channel->queue_bind($exchange_name, $exchange_name); }
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(); }
public function tearDown() { if ($this->ch) { $this->ch->exchange_delete($this->exchange_name); $this->ch->close(); } if ($this->conn) { $this->conn->close(); } }
public function it_properly_pops_job_off_of_rabbitmq(AMQPStreamConnection $connection, AMQPChannel $channel, AMQPMessage $message, Container $container) { $queue = 'default'; $connection->channel()->shouldBeCalled()->willReturn($channel); $channel->exchange_declare($queue, 'direct', false, true, false)->shouldBeCalled(); $channel->queue_declare($queue, false, true, false, false, false, null)->shouldBeCalled(); $channel->queue_bind($queue, $queue, $queue)->shouldBeCalled(); $channel->basic_get($queue)->shouldBeCalled()->willReturn($message); $this->setContainer($container); $this->pop()->shouldHaveType(RabbitMQJob::class); }
protected function initialize_translator() { $connection = new AMQPStreamConnection($this->translator_params['host'], $this->translator_params['port'], $this->translator_params['username'], $this->translator_params['password']); $channel = $connection->channel(); $channel->exchange_declare('bank_translators_exchange', 'direct', false, false, false); list($queue_name, , ) = $channel->queue_declare("", false, false, true, false); $this->translator_params['queue_name'] = $queue_name; $channel->queue_bind($queue_name, 'bank_translators_exchange', $this->translator_params['routing_key']); echo ' [*] Waiting for messages. To exit press CTRL+C', "\n"; $this->translator = array('connection' => $connection, 'channel' => $channel); }
/** * Connects to AMQP and gets channel * * @return AMQPChannel */ private function getChannel() { if (!$this->channel) { $conn = new AMQPStreamConnection($this->connectionOptions['host'], $this->connectionOptions['port'], $this->connectionOptions['user'], $this->connectionOptions['pass'], $this->connectionOptions['vhost']); $ch = $conn->channel(); $ch->exchange_declare($this->exchange, $this->exchangeType, false, true, false); $ch->queue_declare($this->queue, false, true, false, false); $ch->queue_bind($this->queue, $this->exchange, $this->routingKey); $this->channel = $ch; } return $this->channel; }
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(); }
/** * First tries to create exchange using passive flag. * If exchange does not exist, creates new with provided settings. * * @param AMQPStreamConnection $connection AMQP connection. * @param string $name Exchange name. * @param string $type Exchange type. * @param array $params Optional declare exchange parameters. * * @return void * * @see self::$defaultDeclareExchangeParams */ public static function declareExchange(AMQPStreamConnection $connection, $name, $type, array $params = []) { $ch = $connection->channel(); $params = array_merge(self::$defaultDeclareExchangeParams, $params); if ($params['arguments'] and is_array($params['arguments'])) { $params['arguments'] = new AMQPTable($params['arguments']); } try { $ch->exchange_declare($name, $type, false, $params['durable'], $params['auto_delete'], $params['internal'], $params['nowait'], $params['arguments']); } finally { $ch->close(); } }
protected function getChannel() { if (empty($this->channel)) { try { $connection = new AMQPStreamConnection($this->config['host'], $this->config['port'], $this->config['user'], $this->config['password']); } catch (\ErrorException $ee) { sleep(2); return $this->getChannel(); } $this->channel = $connection->channel(); } return $this->channel; }
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(); }
/** * @param string $exchange * @param string $type * @param array $config * @throws ConnectionException */ public function __construct($exchange, $type = 'direct', $config = []) { $this->config = $this->buildConfig($config); $this->exchange = $exchange; $this->type = $type; try { $connection = new AMQPStreamConnection($this->config['host'], $this->config['port'], $this->config['username'], $this->config['password'], $this->config['vhost'], $this->config['connection']['insist'], $this->config['connection']['login_method'], $this->config['connection']['login_response'], $this->config['connection']['locale'], $this->config['connection']['timeout'], $this->config['connection']['read_write_timeout'], $this->config['connection']['context'], $this->config['connection']['keepalive'], $this->config['connection']['heartbeat']); $this->channel = $connection->channel(); $this->channel->exchange_declare($exchange, $type, $this->config['exchange']['passive'], $this->config['exchange']['durable'], $this->config['exchange']['auto_delete'], $this->config['exchange']['internal'], $this->config['exchange']['no_wait'], $this->config['exchange']['arguments'], $this->config['exchange']['ticket']); } catch (\Exception $e) { throw new ConnectionException('Carrot failed to build connection: ' . $e->getMessage()); } }
/** * First tries to create exchange using passive flag. * If exchange does not exist, creates new with provided settings. * * @param \PhpAmqpLib\Connection\AMQPStreamConnection $connection AMQP connection * @param string $name Exchange name * @param string $type Exchange type * @param array $params optional declare exchange parameters * @see self::$defaultDeclareExchangeParams */ public static function declareExchange($connection, $name, $type, $params = []) { $params = array_replace(self::$defaultDeclareExchangeParams, $params); $ch = $connection->channel(); try { $ch->exchange_declare($name, $type, true); } catch (AMQPProtocolChannelException $e) { $ch = $connection->channel(); if ($params['arguments'] and is_array($params['arguments'])) { $params['arguments'] = new AMQPTable($params['arguments']); } $ch->exchange_declare($name, $type, false, $params['durable'], $params['auto_delete'], $params['internal'], $params['nowait'], $params['arguments']); } }
/** * @param AMQPStreamConnection $connection * @param EventBusInterface $eventBus * @param DeserializerLocatorInterface $deserializerLocator * @param StringLiteral $consumerTag * @param StringLiteral $exchangeName * @param StringLiteral $queueName * @param int $delay */ public function __construct(AMQPStreamConnection $connection, EventBusInterface $eventBus, DeserializerLocatorInterface $deserializerLocator, StringLiteral $consumerTag, StringLiteral $exchangeName, StringLiteral $queueName, $delay = 0) { $this->connection = $connection; $this->channel = $connection->channel(); $this->channel->basic_qos(0, 4, true); $this->eventBus = $eventBus; $this->deserializerLocator = $deserializerLocator; $this->queueName = $queueName; $this->consumerTag = $consumerTag; $this->exchangeName = $exchangeName; $this->delay = $delay; $this->declareQueue(); $this->registerConsumeCallback(); }
/** * @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(); }
/** * Return last used channel id during current connection session. * * @return int */ public function getUsedChannels() { if (!$this->isConnected()) { return 0; } return $this->connection->getChannelId(); }
/** * @param bool $forceNewChannell * * @return void */ protected function openChannel($forceNewChannell = false) { if (true == $forceNewChannell || false == $this->channel instanceof AMQPChannel) { $this->channel = $this->connection->channel(); $this->logger->info('New channel opened!', [$this->channel->getChannelId()]); } }
/** * Constucts object. * * @param callable $callback Callable to call for each consumed event. * @param AMQPStreamConnection $connection AMQP connection object. * @param string $queue Queue to bind. * @param string $exchange An events exchange. * @param string $bindingKey A binding key. * * @throws ErrorException On network\transport errors. */ public function __construct(callable $callback, AMQPStreamConnection $connection, $queue, $exchange, $bindingKey) { // TODO: consumer shoud has own connection with heartbeat. // The heartbeat is checked only during IO operations, so when AMQP connection // not used for a long time, RabbitMQ terminates connection $this->queue = $queue; $this->bindingKey = $bindingKey; $this->channel = $connection->channel(); Util::declareQueue($connection, $queue, ['durable' => true, 'exclusive' => false]); Util::declareExchange($connection, $exchange, 'direct', ['auto_delete' => false]); $ch->queue_bind($queue, $exchange, $bindingKey); $wrapper = function ($msg) use($callback) { $event = new Event($msg); return $callback($event); }; $ch->basic_consume($this->queue, '', false, false, false, false, $wrapper); }
/** * Disconnects from the message broker */ public function disconnect() { if ($this->connection !== null) { $this->channel->close(); $this->connection->close(); } return $this; }
/** * @param AMQPStreamConnection $connection * @param string $exchange * @param array $defaultMessageParams */ public function __construct(AMQPStreamConnection $connection, $exchange, array $defaultMessageParams = null) { $this->connection = $connection; $this->exchange = $exchange; $this->defaultMessageParams = $defaultMessageParams; $this->channel = $this->connection->channel(); }
public function __construct() { $this->connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $this->channel = $this->connection->channel(); list($this->callback_queue, , ) = $this->channel->queue_declare("", false, false, true, false); $this->channel->basic_consume($this->callback_queue, '', false, false, false, false, [$this, 'on_response']); }
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(); }