protected function setUp() { $this->client = HttpClient::factory(array('host' => 'localhost')); $this->object = new APIClient($this->client); $this->conn = new \PhpAmqpLib\Connection\AMQPConnection('localhost', 5672, 'guest', 'guest', '/'); $this->channel = $this->conn->channel(); }
/** * Create service with name * * @param ServiceLocatorInterface $serviceLocator * @param $name * @param $requestedName * @return mixed */ public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) { $name = substr($requestedName, strlen(self::MANAGER_PREFIX)); $config = $serviceLocator->get('config'); $workerConfig = $config['workers'][$name]; if (!$serviceLocator->has($workerConfig['manager']['director'])) { throw new \RuntimeException("Could not load {$workerConfig['manager']['director']}"); } $director = $serviceLocator->get($workerConfig['manager']['director']); if (!$director instanceof DirectorInterface) { throw new \RuntimeException("Could not load {$workerConfig['manager']['director']}"); } $rabbitMqSettings = isset($workerConfig['rabbitmq_settings']) ? $workerConfig['rabbitmq_settings'] : $config['rabbitmq_settings']; $conn = new AMQPConnection($rabbitMqSettings['host'], $rabbitMqSettings['port'], $rabbitMqSettings['username'], $rabbitMqSettings['password']); // Bind to the generic exchange $eventChannel = $conn->channel(); $exchange = $workerConfig['manager']['general']['exchange']['name']; $exchangeType = $workerConfig['manager']['general']['exchange']['type']; $eventQueueName = $workerConfig['manager']['general']['queue']['name']; $routingKey = isset($workerConfig['manager']['general']['queue']['routing_key']) ? $workerConfig['manager']['general']['queue']['routing_key'] : null; $eventChannel->queue_declare($eventQueueName, false, true, false, false); $eventChannel->exchange_declare($exchange, $exchangeType, false, false, true); $eventChannel->queue_bind($eventQueueName, $exchange, $routingKey); // Bind to the one specific for the workers $processorQueueName = $workerConfig['manager']['worker']['queue']['name']; $workerExchange = $workerConfig['manager']['worker']['exchange']['name']; $workerExchangeType = $workerConfig['manager']['worker']['exchange']['type']; $workerChannel = $conn->channel(); $workerChannel->exchange_declare($workerExchange, $workerExchangeType, false, false, false); $workerChannel->queue_declare($processorQueueName, false, true, false, false); $workerChannel->queue_bind($processorQueueName, $workerExchange); return new DirectedManager($conn, $eventChannel, $eventQueueName, $workerChannel, $workerExchange, $processorQueueName, $director); }
protected function setupConnection() { Yii::trace('Connecting to broker...', __METHOD__); $this->connection = new AMQPConnection($this->host, $this->port, $this->user, $this->password, $this->vhost, $this->insist, $this->login_method, $this->login_response, $this->locale, $this->connection_timeout, $this->read_write_timeout, $this->context); $this->channel = $this->connection->channel(); $this->channel->queue_declare($this->queue, false, true, false, false); }
private function __construct() { $this->connection = new AMQPConnection($this->connection_host, $this->connection_port, $this->connection_user, $this->connection_password); $this->channel = $this->connection->channel(); $this->channel->queue_declare('task_queue_persistent', false, true, false, false); return $this; }
public function setUp() { $this->conn = new AMQPConnection(HOST, PORT, USER, PASS, VHOST); $this->ch = $this->conn->channel(); $this->ch->exchange_declare($this->exchange_name, 'direct', false, false, false); list($this->queue_name, , ) = $this->ch->queue_declare(); $this->ch->queue_bind($this->queue_name, $this->exchange_name, $this->queue_name); }
/** * @return AMQPChannelannel */ public function getChannel() { if (!$this->channel) { $this->connection = new AMQPConnection($this->settings['host'], $this->settings['port'], $this->settings['user'], $this->settings['pass'], $this->settings['vhost']); $this->channel = $this->connection->channel(); register_shutdown_function(array($this, 'shutdown')); } return $this->channel; }
public function connect() { $this->logger->info("MqService connecting..."); $this->connection = $this->connectionFactory->createConnection($this->options); $this->channel = $this->connection->channel(); $this->exchangeDeclare(); $this->isConnected = true; $this->logger->info("MqService connected"); }
/** * @param string $queue * @param HttpRequest $httpRequest */ public function start($queue, HttpRequest $httpRequest) { $this->queue = $queue; $this->httpRequest = $httpRequest; $this->connection = new AMQPConnection($this->host, $this->port, $this->user, $this->pass); $this->channel = $this->connection->channel(); list(, , $consumer_count) = $this->channel->queue_declare($this->queue, false, false, false, false); $this->consumer_count = $consumer_count; }
/** * Creates (if not yet created) and returns an AMQP channel. * * @return \PhpAmqpLib\Channel\AMQPChannel */ protected function getChannel() { if (null === $this->channel) { $this->channel = $this->connection->channel(); $this->channel->queue_declare($this->queueName, false, false, false, false); $this->channel->basic_qos(null, 1, null); } return $this->channel; }
protected function setUp() { $this->loop = \React\EventLoop\Factory::create(); $this->object = AsyncAPIClient::factory($this->loop, array('host' => '127.0.0.1')); $this->syncClientClient = HttpClient::factory(array('host' => 'localhost')); $this->syncClient = new APIClient($this->syncClientClient); $this->conn = new \PhpAmqpLib\Connection\AMQPConnection('localhost', 5672, 'guest', 'guest', '/'); $this->channel = $this->conn->channel(); }
/** * {@inheritdoc} */ public function commit() { $channel = $this->connection->channel(); $channel->queue_declare($this->options->getQueue(), false, false, false, false); while (!$this->messages->isEmpty()) { $channel->batch_basic_publish(new AMQPMessage(serialize($this->messages->dequeue())), '', $this->options->getQueue()); } $channel->publish_batch(); $channel->close(); }
/** * Open a connection with the RabbitMQ Server * * @return void */ public function open() { try { $this->AMQPConnection = new AMQPConnection($this->host, $this->port, $this->username, $this->password, $this->vhost); $this->channel = $this->AMQPConnection->channel(); $this->channel->queue_declare($this->queue_name, false, true, false, false); $this->channel->exchange_declare($this->queue_name, 'x-delayed-message', false, true, false, false, false, new AMQPTable(["x-delayed-type" => "direct"])); $this->channel->queue_bind($this->queue_name, $this->queue_name); } catch (Exception $e) { throw new Exception($e); } }
/** * Open a connection with the RabbitMQ Server * * @return void */ public function open() { try { $this->AMQPConnection = new AMQPConnection($this->host, $this->port, $this->username, $this->password, $this->vhost); $this->channel = $this->AMQPConnection->channel(); $this->channel->queue_declare($this->queue_name, false, true, false, false); $this->channel->exchange_declare($this->exchange, 'direct', false, true, false); $this->channel->queue_bind($this->queue_name, $this->exchange); } catch (Exception $e) { throw new Exception($e); } }
public function subscribe(Consumer $consumer, ExecutionCondition $condition) { $this->consumer = $consumer; $this->condition = $condition; $channel = $this->client->channel(); $channel->basic_consume($consumer->getConfig()->getDestination(), '', false, false, false, false, [$this, 'callback']); while ($condition->isValid()) { try { $channel->wait(null, null, 10); } catch (AMQPTimeoutException $e) { } } }
/** * getChannel * * @param string $connection * * @return AMQPChannel */ protected function getChannel($connection) { if (isset($this->channels[$connection])) { return $this->channels[$connection]; } if (!isset($this->connections[$connection])) { throw new \InvalidArgumentException(sprintf('Unknown connection "%s". Available: [%s]', $connection, implode(', ', array_keys($this->connections)))); } if (!isset($this->channels[$connection])) { $this->channels[$connection] = array(); } if (isset($this->connections[$connection]['ssl']) && $this->connections[$connection]['ssl']) { if (empty($this->connections[$connection]['ssl_options'])) { $ssl_opts = array('verify_peer' => true); } else { $ssl_opts = array(); foreach ($this->connections[$connection]['ssl_options'] as $key => $value) { if (!empty($value)) { $ssl_opts[$key] = $value; } } } $conn = new AMQPSSLConnection($this->connections[$connection]['host'], $this->connections[$connection]['port'], $this->connections[$connection]['login'], $this->connections[$connection]['password'], $this->connections[$connection]['vhost'], $ssl_opts); } else { $conn = new AMQPConnection($this->connections[$connection]['host'], $this->connections[$connection]['port'], $this->connections[$connection]['login'], $this->connections[$connection]['password'], $this->connections[$connection]['vhost']); } //$conn->connect(); $this->channels[$connection] = $conn->channel(); return $this->channels[$connection]; }
public function procesoAction() { $this->mqconf = new \Phalcon\Config\Adapter\Ini(CONFIG_PATH . DIRS . "ini/mq.ini"); $connection = new AMQPConnection($this->mqconf->host, $this->mqconf->port, $this->mqconf->user, $this->mqconf->pasw); $channel = $connection->channel(); $channel->queue_declare(SITESLUG . '_widget', false, true, false, false); echo ' [*] Servicio listener para widgets , CTRL+C para cancelar', "\n"; $callback = function ($msg) { try { $data = json_decode($msg->body); echo $data->widget; $method = "widget_{$data->widget}"; unset($data->widget); if (method_exists($this, $method)) { $this->{$method}($data); } } catch (\Exception $e) { var_dump($e); } }; $channel->basic_consume(SITESLUG . '_widget', '', false, true, false, false, $callback); while (count($channel->callbacks)) { $channel->wait(); } }
protected function getConnection() { $connection = new AMQPConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare('email_queue', false, false, false, false); return $channel; }
public function publish_msg($data) { $conn = new AMQPConnection(HOST, PORT, USER, PASS, VHOST); $ch = $conn->channel(); $msg = new AMQPMessage(json_encode($data), array('content_type' => 'text/plain', 'delivery_mode' => 2)); $rtn = $ch->basic_publish($msg, "inStock"); }
/** * * Bootstraps the connection and the channel * * @throws \GraphAware\SimpleMQ\Exception\SimpleMQException */ public function run() { $conn = $this->getExchange()->getConnection(); try { $this->connection = new AMQPConnection($conn->getHost(), $conn->getPort(), $conn->getUser(), $conn->getPassword(), $conn->getVhost()); $this->channel = $this->connection->channel(); } catch (AMQPRuntimeException $e) { throw new SimpleMQException($e->getMessage()); } catch (AMQPProtocolException $e) { throw new SimpleMQException($e->getMessage()); } $this->channel->exchange_declare($this->getExchange()->getName(), $this->getExchange()->getType(), false, $this->getExchange()->isIsDurable()); if ($this->getExchange()->isIsDurable()) { $this->properties['delivery_mode'] = 2; } }
function processvideo() { $this->load->config('amqp'); $exchange = 'video'; $queue = 'video_q'; $consumer_tag = 'consumer'; $connection = new AMQPConnection($this->config->item('host'), $this->config->item('port'), $channel = $this->config->item('user'), $channel = $this->config->item('pass'), "/"); $channel = $connection->channel(); $channel->queue_declare($queue, false, true, false, false); $callback = function ($msg) { print_r($msg); die; $collection = $this->mongo_db->db->selectCollection('video'); $result = $collection->update(["video_id" => $msg->video_id], ["status" => "processing"]); sleep(range(5, 10)); $start_date = new DateTime('2000-01-01 ' . $msg->start_time); $since_start = $start_date->diff(new DateTime('2012-09-11 ' . $msg->end_time)); $video_len = $since_start->h . ":" . $since_start->i . ":" . $since_start->s; $result = $collection->update(["video_id" => $msg->video_id], ["status" => "done", "link" => "https://youtube.com?dffd", "video_len" => $video_len]); $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']); }; $channel->basic_qos(null, 1, null); $channel->basic_consume($queue, '', false, false, false, false, $callback); while (count($channel->callbacks)) { $channel->wait(); } $channel->close(); $connection->close(); }
public function makeAction() { $this->mqconf = new \Phalcon\Config\Adapter\Ini(CONFIG_PATH . DIRS . "ini/mq.ini"); $connection = new AMQPConnection($this->mqconf->host, $this->mqconf->port, $this->mqconf->user, $this->mqconf->pasw); $channel = $connection->channel(); $channel->queue_declare(SITESLUG . '_sondeo', false, true, false, false); echo ' [*] Servicio listener de sondeos iniciado , CTRL+C para cancelar', "\n"; $callback = function ($msg) { try { $vars = json_decode($msg->body); var_dump($vars); \Rpp\Services\Get\Elecciones::$pattern = null; \Rpp\Services\Get\Elecciones::$sondeos = null; $sondeo = \Rpp\Services\Get\Elecciones::get($vars->id); var_dump($sondeo); } catch (\Exception $e) { var_dump($e); } break; }; $channel->basic_consume(SITESLUG . '_sondeo', '', false, true, false, false, $callback); while (count($channel->callbacks)) { $channel->wait(); } }
public function portadaAction() { $this->mqconf = new \Phalcon\Config\Adapter\Ini(CONFIG_PATH . DIRS . "ini/mq.ini"); $connection = new AMQPConnection($this->mqconf->host, $this->mqconf->port, $this->mqconf->user, $this->mqconf->pasw); $channel = $connection->channel(); $channel->queue_declare(SITESLUG . '_publicacion_destacados', false, true, false, false); echo ' [*] Servicio listener para la publicacion de destacados , CTRL+C para cancelar', "\n"; $callback = function ($msg) { try { $node = json_decode($msg->body); print_r($node); $destacados = new \Rpp\Services\Publish\Destacados(@$node->slug); $di = new Phalcon\DI(); $di->set('viewCache', $this->viewCache); $destacados->setDI($di); $destacados->load(); } catch (\Exception $e) { var_dump($e); } break; }; $channel->basic_consume(SITESLUG . '_publicacion_destacados', '', false, true, false, false, $callback); while (count($channel->callbacks)) { $channel->wait(); } }
public function publish(array $events) { if (null === $this->connection) { throw new \RuntimeException("The AMQPTerminal has no connection configured."); } $channel = $this->connection->channel(); if ($this->isTransactional) { $channel->tx_select(); } try { if ($this->waitForAck) { $channel->confirm_select(); } foreach ($events as $event) { $amqpMessage = $this->messageConverter->createAmqpMessage($event); $this->doSendMessage($channel, $amqpMessage); } if (CurrentUnitOfWork::isStarted()) { CurrentUnitOfWork::get()->registerListener(new ChannelTransactionUnitOfWorkListener($this->logger, $channel, $this)); } elseif ($this->isTransactional) { $channel->tx_commit(); } elseif ($this->waitForAck) { $channel->wait_for_pending_acks($this->publisherAckTimeout); } } catch (\Exception $ex) { if ($this->isTransactional) { $this->tryRollback($channel); } throw new EventPublicationFailedException("Failed to dispatch Events to the Message Broker.", 0, $ex); } finally { if (!CurrentUnitOfWork::isStarted()) { $this->tryClose($channel); } } }
/** * Process incoming request to generate pdf invoices and send them through * email. */ public function listen() { $this->log->addInfo('Begin listen routine'); $connection = new AMQPConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare('invoice_queue', false, true, false, false); /** * don't dispatch a new message to a worker until it has processed and * acknowledged the previous one. Instead, it will dispatch it to the * next worker that is not still busy. */ $channel->basic_qos(null, 1, null); /** * indicate interest in consuming messages from a particular queue. When they do * so, we say that they register a consumer or, simply put, subscribe to a queue. * Each consumer (subscription) has an identifier called a consumer tag */ $channel->basic_consume('invoice_queue', '', false, false, false, false, array($this, 'process')); $this->log->addInfo('Consuming from queue'); while (count($channel->callbacks)) { $this->log->addInfo('Waiting for incoming messages'); $channel->wait(); } $channel->close(); $connection->close(); }
public function notasAction() { $this->mqconf = new \Phalcon\Config\Adapter\Ini(CONFIG_PATH . DIRS . "ini/mq.ini"); $connection = new AMQPConnection($this->mqconf->host, $this->mqconf->port, $this->mqconf->user, $this->mqconf->pasw); $channel = $connection->channel(); $channel->queue_declare(SITESLUG . '_eliminar_noticia', false, true, false, false); echo ' [*] Servicio listener para despublicacion , CTRL+C para cancelar', "\n"; $callback = function ($msg) { try { $node = json_decode($msg->body); var_dump($node); $publicacion = new \Rpp\Services\Unpublish\Noticia((int) $node->nid); $di = new Phalcon\DI(); $di->set('viewCache', $this->viewCache); $publicacion->setDI($di); $publicacion->builder(); } catch (\Exception $e) { var_dump($e); } break; }; $channel->basic_consume(SITESLUG . '_eliminar_noticia', '', false, true, false, false, $callback); while (count($channel->callbacks)) { $channel->wait(); } }
/** * @param $config * @throws Kontoulis\RabbitMQLaravel\Exception\BrokerException */ function __construct($config) { $this->host = $config['amqp_host']; $this->port = $config['amqp_port']; $this->user = $config['amqp_user']; $this->password = $config['amqp_pass']; $this->vhost = $config['amqp_vhost']; $this->queueName = $config["amqp_queue"]; try { /* Open RabbitMQ connection */ $this->connection = new AMQPConnection($this->host, $this->port, $this->user, $this->password, $this->vhost); $this->channel = $this->connection->channel(); } catch (AMQPRuntimeException $ex) { throw new BrokerException('Fatal error while initializing AMQP connection: ' . $ex->getMessage(), $ex->getCode()); } }
public function actionIndex() { $connection = new AMQPConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->exchange_declare('images', 'direct', false, false, false); list($queue_name, , ) = $channel->queue_declare("", false, false, true, false); $channel->queue_bind($queue_name, 'images', 'images routing key'); $channel2 = $connection->channel(); $channel2->exchange_declare('files', 'fanout', false, false, false); $callback = function ($msg) use($channel2) { $data = json_decode($msg->body); $width = ImagesHelper::width($data->source); $height = ImagesHelper::height($data->source); // создание миниатюры изображения $thumbWidth = 207; // ширина будущего изображения в px $thumbHeight = $thumbWidth * $height / $width; // высота будущего изображения в px if ($fixResizedImage = ImagesHelper::resize($data->source, $thumbWidth, $thumbHeight)) { // сохранение полученного изображения $widthThumb = ImagesHelper::save($fixResizedImage, $data->source, 'w_207_', $data->extension); } // создание миниатюры изображения $thumbHeight = 207; // высота будущего изображения в px $thumbWidth = $thumbHeight * $width / $height; // ширина будущего изображения в px if ($fixResizedImage2 = ImagesHelper::resize($data->source, $thumbWidth, $thumbHeight)) { // сохранение полученного изображения $heightThumb = ImagesHelper::save($fixResizedImage2, $data->source, 'h_207_', $data->extension); } $image = ['type' => 'file', 'data' => ['name' => $data->name, 'widthThumb' => DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'w_207_' . $data->name . '.' . $data->extension, 'heightThumb' => DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'h_207_' . $data->name . '.' . $data->extension]]; $msg = new AMQPMessage(json_encode($image)); $channel2->basic_publish($msg, 'files'); }; /* * 4-й - false - по ум-ю (то есть все сообщ-я хранятся в очереди всегда, * даже после прочтения), если true - то сообщ-е уд-ся из очереди сразу после прочтения */ /**/ $channel->basic_consume($queue_name, '', false, true, false, false, $callback); while (count($channel->callbacks)) { $channel->wait(); } $channel->close(); $connection->close(); }
/** * @inheritdoc */ public function init() { parent::init(); if ($this->config === null) { throw new InvalidConfigException('The "config" property must be set.'); } if (!$this->amqp instanceof AMQPConnection) { $this->amqp = new AMQPConnection($this->config['host'], $this->config['port'], $this->config['username'], $this->config['password'], $this->config['vhost']); } if (!$this->channel) { $this->channel = $this->amqp->channel(); } register_shutdown_function(array($this, 'shutdown')); if ($this->exchange) { $this->channel->exchange_declare($this->exchange, $this->exchangeType, false, false, false); } }
function publish($data) { $conn = new AMQPConnection(HOST, PORT, USER, PASS, VHOST); $ch = $conn->channel(); $ch->queue_declare("oversold_queue", false, true, false, false); $ch->queue_bind("oversold_queue", "oversold"); $msg = new AMQPMessage(json_encode($data), array('content_type' => 'text/plain', 'delivery_mode' => 2)); $rtn = $ch->basic_publish($msg, "oversold"); }
/** * Perform the check * * @see \ZendDiagnostics\Check\CheckInterface::check() * @return Failure|Success */ public function check() { if (!class_exists('PhpAmqpLib\\Connection\\AMQPConnection')) { return new Failure('PhpAmqpLib is not installed'); } $conn = new AMQPConnection($this->host, $this->port, $this->user, $this->password, $this->vhost); $conn->channel(); return new Success(); }