/** * @return \AMQPQueue */ public function getSrvQueue() { if ($this->srvQueue === null) { $chanel = $this->getChanel(); /* create a queue object */ $this->srvQueue = new \AMQPQueue($chanel); $this->srvQueue->setName($this->queueName); $this->srvQueue->setFlags(AMQP_DURABLE); $this->srvQueue->declareQueue(); } return $this->srvQueue; }
protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln(sprintf('Move messages from queue "%s" (vhost: "%s") to exchange "%s" with routingKey "%s" (vhost: "%s")', $input->getArgument('from_queue'), $input->getArgument('from_vhost'), $input->getArgument('to_exchange'), $input->getArgument('to_routing_key'), $input->getArgument('to_vhost'))); $fromChannel = $this->getChannel($input->getArgument('from_connection'), $input->getArgument('from_vhost')); if (null === ($toConnectionName = $input->getOption('to_connection'))) { $toChannel = $this->getChannel($input->getArgument('from_connection'), $input->getArgument('to_vhost')); } else { $toChannel = $this->getChannel($input->getOption('to_connection'), $input->getArgument('to_vhost')); } $queue = new \AMQPQueue($fromChannel); $queue->setName($input->getArgument('from_queue')); $exchange = new \AMQPExchange($toChannel); $exchange->setName($input->getArgument('to_exchange')); $messageProvider = new PeclPackageMessageProvider($queue); $messagePublisher = new PeclPackageMessagePublisher($exchange); $options = array(); $stack = new \Swarrot\Processor\Stack\Builder(); if (0 !== ($max = (int) $input->getOption('max-messages'))) { $stack->push('Swarrot\\Processor\\MaxMessages\\MaxMessagesProcessor'); $options['max_messages'] = $max; } $stack->push('Swarrot\\Processor\\Insomniac\\InsomniacProcessor'); $stack->push('Swarrot\\Processor\\Ack\\AckProcessor', $messageProvider); $processor = $stack->resolve(new MoveProcessor($messagePublisher, $input->getArgument('to_routing_key'))); $consumer = new Consumer($messageProvider, $processor); $consumer->consume($options); }
private function _initPublisher() { if (!$this->open()) { return false; } if ($this->_exchange) { return true; } $channel = new AMQPChannel($this->_conn); //创建exchange $this->_exchange = new AMQPExchange($channel); $this->_exchange->setName($this->_connInfo['exchangeName']); $this->_exchange->setType(AMQP_EX_TYPE_DIRECT); $this->_exchange->setFlags(AMQP_DURABLE); if (!$this->_exchange->declareExchange()) { $this->close(); return false; } //创建队列,生产者和消费者都要创建队列 $queue = new AMQPQueue($channel); $queue->setName($this->_connInfo['queueName']); $queue->setFlags(AMQP_DURABLE); $queue->declareQueue(); $queue->bind($this->_connInfo['exchangeName'], $this->_connInfo['routingKey']); return true; }
public function declareQueue($name, $flags = AMQP_DURABLE) { $queue = new \AMQPQueue($this->channel); $queue->setName($name); $queue->setFlags($flags); $queue->declareQueue(); return $queue; }
protected function getAMQPQueue($name) { $connection = new \AMQPConnection(array('vhost' => 'swarrot')); $connection->connect(); $channel = new \AMQPChannel($connection); $queue = new \AMQPQueue($channel); $queue->setName($name); return $queue; }
/** * {@inheritDoc} */ public function register(Container $c) { $c['amqp.connections.initializer'] = function ($c) { $config = $c['amqp.options']; $connections = array(); if (isset($config['connections'])) { foreach ($config['connections'] as $name => $options) { $connections[$name] = new \AMQPConnection($options); } return $connections; } if (isset($config['connection'])) { return array('default' => new \AMQPConnection($config['connection'])); } throw new \LogicException('No connection defined'); }; $c['queue.factory'] = function ($c) { $connections = $c['amqp.connections.initializer']; return function ($queueName, $connectionName = null) use($connections) { $names = array_keys($connections); if (null === $connectionName) { $connectionName = reset($names); } if (!array_key_exists($connectionName, $connections)) { throw new \InvalidArgumentException(sprintf('Unknown connection "%s". Available: [%s]', $connectionName, implode(', ', $names))); } $connection = $connections[$connectionName]; if (!$connection->isConnected()) { $connection->connect(); } $channel = new \AMQPChannel($connection); $queue = new \AMQPQueue($channel); $queue->setName($queueName); return $queue; }; }; $c['exchange.factory'] = function ($c) { $connections = $c['amqp.connections.initializer']; return function ($exchangeName, $connectionName = null) use($connections) { $names = array_keys($connections); if (null === $connectionName) { $connectionName = reset($names); } if (!array_key_exists($connectionName, $connections)) { throw new \InvalidArgumentException(sprintf('Unknown connection "%s". Available: [%s]', $connectionName, implode(', ', $names))); } $connection = $connections[$connectionName]; if (!$connection->isConnected()) { $connection->connect(); } $channel = new \AMQPChannel($connection); $exchange = new \AMQPExchange($channel); $exchange->setName($exchangeName); return $exchange; }; }; }
/** * @param string $name * * @return \AMQPQueue */ protected function getQueue($name) { if (!isset($this->queues[$name])) { $queue = new \AMQPQueue($this->getChannel()); $queue->setName($name); $this->queues[$name] = $queue; } return $this->queues[$name]; }
public function get($queueName, $timeout = null) { if (null === $this->queue) { $queue = new \AMQPQueue($this->channel); $queue->setName($queueName); $queue->declare(); } return unserialize($queue->consume()); }
/** * @inheritdoc */ public function createQueue(ChannelInterface $channel, $name = null, $flags = null, array $args = []) { $delegate = new \AMQPQueue($channel->getDelegate()); $delegate->setFlags(Queue::convertToDelegateFlags($flags)); $delegate->setArguments($args); if (null !== $name) { $delegate->setName($name); } return new Queue($delegate, $channel); }
/** * AMQP queue initialization * @param string $name Queue name * @param string $mode Access mode: r is for reading and w is for writing * @return \AMQPQueue */ public function init($name, $mode = 'w') { $queue = new \AMQPQueue($this->channel); $queue->setName($name); $queue->declare(); if ($mode == 'r') { $queue->bind('Celium', $name); } return $queue; }
/** * @return \AMQPQueue */ protected function getQueue() { if (!$this->queue) { $this->queue = new \AMQPQueue($this->getChannel()); $this->queue->setName($this->queueConfig['name']); $this->queue->setFlags($this->queueConfig['flags']); $this->queue->declareQueue(); } return $this->queue; }
public function take() { $q = new \AMQPQueue($this->amqpChannel); $q->setName($this->name); $msg = $q->get(); if (empty($msg)) { return false; } else { return new MessageTakeControl($q, $msg); } }
/** * getQueue. * * @param string $name * @param string $connection * * @return \AMQPQueue */ public function getQueue($name, $connection) { if (!isset($this->queues[$connection][$name])) { if (!isset($this->queues[$connection])) { $this->queues[$connection] = array(); } $queue = new \AMQPQueue($this->getChannel($connection)); $queue->setName($name); $this->queues[$connection][$name] = $queue; } return $this->queues[$connection][$name]; }
public function it_should_initialize(\AMQPQueue $queue, Exchange $exchange, Context $context) { $exchange->getName()->willReturn('exchange'); $context->getFlags()->willReturn(1234); $context->getArguments()->willReturn(['foo' => 'bar']); $queue->setName('queue')->shouldBeCalled(); $queue->bind('exchange')->shouldBeCalled(); $queue->setFlags(1234)->shouldBeCalled(); $queue->setArguments(['foo' => 'bar'])->shouldBeCalled(); $queue->declareQueue()->shouldBeCalled(); $this->initialize($queue); $this->isInitialized()->shouldReturn(true); }
public function subscribe($topic, $queueName, $process_callback) { $channel = new AMQPChannel($this->amqpConnection); $channel->setPrefetchCount(0); $queue = new AMQPQueue($channel); $queue->setName($queueName); $queue->setFlags(AMQP_DURABLE); $queue->declareQueue(); $queue->bind('topic', $topic); $queue->consume($process_callback); if (!$this->amqpConnection->disconnect()) { throw new Exception("Could not disconnect !"); } }
/** * Get transport queue for current channel. * @return AMQPQueue */ protected function _getQueue() { if (!$this->_queue) { //创建队列 $this->_queue = new \AMQPQueue($this->_getChannel()); //设置队列名字 如果不存在则添加 $this->_queue->setName($this->_params['queue']); $this->_queue->setFlags(AMQP_DURABLE | AMQP_AUTODELETE); $this->_queue->declareQueue(); //将你的队列绑定到routingKey $this->_queue->bind($this->_params['exchange'], $this->_params['router']); } return $this->_queue; }
public static function setupConnection(\AMQPConnection $connection, $config) { $channel = new \AMQPChannel($connection); $exchange = new \AMQPExchange($channel); $exchange->setName($config['exchange_name']); $exchange->setType(AMQP_EX_TYPE_DIRECT); $exchange->setFlags(AMQP_DURABLE); $exchange->declareExchange(); $queue = new \AMQPQueue($channel); $queue->setName($config['queue_name']); $queue->setFlags(AMQP_DURABLE); $queue->declareQueue(); // $exchange->bind($config['queue_name'], 'gos.websocket.pusher'); return [$channel, $exchange, $queue]; }
/** * {@inheritDoc} */ protected function setUpAmqp() { $this->conn = new \AMQPConnection(['host' => $_SERVER['AMQP_HOST'], 'port' => $_SERVER['AMQP_PORT'], 'login' => $_SERVER['AMQP_USER'], 'password' => $_SERVER['AMQP_PASS'], 'vhost' => $_SERVER['AMQP_VHOST']]); $this->conn->connect(); $channel = new \AMQPChannel($this->conn); $exchange = new \AMQPExchange($channel); $exchange->setName('event_band.test.exchange'); $exchange->setFlags(AMQP_AUTODELETE); $exchange->setType(AMQP_EX_TYPE_TOPIC); $exchange->declareExchange(); $queue = new \AMQPQueue($channel); $queue->setName('event_band.test.event'); $queue->declareQueue(); $queue->bind('event_band.test.exchange', 'event.#'); }
public function consume($queueName, $callBackFunction) { try { $queue = new AMQPQueue($this->channel); $queue->setName($queueName); $queue->setFlags(AMQP_DURABLE); $queue->declareQueue(); echo ' [*] Waiting for messages on ' . $queueName . '. To exit press CTRL+C ', PHP_EOL; $queue->consume($callBackFunction); } catch (AMQPQueueException $ex) { print_r($ex); } catch (Exception $ex) { print_r($ex); } }
/** * @param \AMQPQueue|null $queue * * @throws HectorException */ public function initialize(\AMQPQueue $queue = null) { if (true === $this->isInitialized()) { throw new HectorException('Queue already initialized'); } if (null === $queue) { $queue = new \AMQPQueue($this->channel->getWrappedChannel()); } $this->queue = $queue; $this->queue->setName($this->getName()); $this->queue->bind($this->exchange->getName()); $this->queue->setFlags($this->context->getFlags()); $this->queue->setArguments($this->context->getArguments()); $this->queue->declareQueue(); $this->initialized = true; }
/** * @param $queueName * @return AMQPQueue */ public function getQueue($queueName) { return $this->container->asSingleton(__METHOD__ . $queueName, function () use($queueName) { QueueEnum::validate($queueName); $queue = null; $connection = $this->getConnection(TypeEnum::READ); if ($connection) { if (class_exists('AMQPChannel')) { // AMQP Version 1.0 $channel = new AMQPChannel($connection); $queue = new AMQPQueue($channel); $queue->setName($queueName); } else { $queue = new AMQPQueue($connection, $queueName); } } return $queue; }); }
public static function main() { self::$pool = new Pool(MAX_CONCURRENCY_JOB, \CALLWorker::class, []); $conn_args = (require 'mq.config.php'); $e_name = 'e_linvo'; //交换机名 $q_name = 'q_linvo'; //队列名 $k_route = 'key_1'; //路由key //创建连接和channel $conn = new AMQPConnection($conn_args); if (!$conn->connect()) { write_log('mq.hx9999.com 无法连接上'); return; } $channel = new AMQPChannel($conn); //创建交换机 $ex = new AMQPExchange($channel); $ex->setName($e_name); $ex->setType(AMQP_EX_TYPE_DIRECT); //direct类型 $ex->setFlags(AMQP_DURABLE); //持久化 //创建队列 $q = new AMQPQueue($channel); $q->setName($q_name); $q->setFlags(AMQP_DURABLE); //持久化 while (True) { $q->consume(function ($envelope, $queue) { $msg = $envelope->getBody(); $queue->ack($envelope->getDeliveryTag()); //手动发送ACK应答 self::$pool->submit(new Sendsms($msg)); }); } self::$pool->shutdown(); $conn->disconnect(); //睡眠 sleep(5); }
/** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln(sprintf('Get %d messages from queue "%s"', $input->getOption('nb-messages'), $input->getArgument('queue'))); $fromChannel = $this->getChannel($input->getArgument('connection'), $input->getArgument('vhost')); $queue = new \AMQPQueue($fromChannel); $queue->setName($input->getArgument('queue')); $noRequeue = $input->getOption('no-requeue'); $nbMessages = $input->getOption('nb-messages'); for ($i = 0; $i < $nbMessages; $i++) { if ($noRequeue) { $message = $queue->get(AMQP_AUTOACK); } else { $message = $queue->get(); } if (false === $message) { $output->writeln('No more messages in queue.'); return; } $output->writeln(print_r($message, true)); } }
public function send($msg) { $channel = new \AMQPChannel($this->connection); $exchange = new \AMQPExchange($channel); $exchange->setFlags(AMQP_DURABLE); $exchange->setName('exchange2'); $exchange->setType('direct'); //$exchange->declare(); $exchange->declareExchange(); $queue = new \AMQPQueue($channel); $queue->setName('series'); $queue->setFlags(AMQP_DURABLE | AMQP_AUTODELETE); //$queue->declare(); $queue->declareQueue(); $queue->bind('exchange2', 'series'); $channel->startTransaction(); $message = $exchange->publish(json_encode($msg), 'series', AMQP_MANDATORY, array('content_type' => 'application/json', 'delivery_mode' => 2)); $channel->commitTransaction(); if (!$message) { throw new \SYSTEM\LOG\ERROR("Error: Message '" . $message . "' was not sent to queue.!"); } }
/** * Return result of task execution for $task_id * @param AMQPConnection $connection Connection object * @param string $task_id Celery task identifier * @param boolean $removeMessageFromQueue whether to remove message from queue * @return array array('body' => JSON-encoded message body, 'complete_result' => AMQPEnvelope object) * or false if result not ready yet */ function GetMessageBody($connection, $task_id, $removeMessageFromQueue = true) { $this->Connect($connection); $ch = $connection->channel; $q = new AMQPQueue($ch); $q->setName($task_id); $q->setFlags(AMQP_AUTODELETE | AMQP_DURABLE); $q->declareQueue(); try { $q->bind('celeryresults', $task_id); } catch (AMQPQueueException $e) { if ($removeMessageFromQueue) { $q->delete(); } $connection->disconnect(); return false; } $message = $q->get(AMQP_AUTOACK); if (!$message) { if ($removeMessageFromQueue) { $q->delete(); } $connection->disconnect(); return false; } if ($message->getContentType() != 'application/json') { if ($removeMessageFromQueue) { $q->delete(); } $connection->disconnect(); throw new CeleryException('Response was not encoded using JSON - found ' . $message->getContentType() . ' - check your CELERY_RESULT_SERIALIZER setting!'); } if ($removeMessageFromQueue) { $q->delete(); } $connection->disconnect(); return array('complete_result' => $message, 'body' => $message->getBody()); }
/** * Create new instance from options * * @param NotificationInterface $notification * @param array $options * * @return Amqp */ public static function create(NotificationInterface $notification, array $options = array()) { $options += array('host' => '127.0.0.1', 'port' => 5672, 'vhost' => '/', 'login' => 'guest', 'password' => 'guest', 'queue_name' => 'apn.push.queue', 'publish_options' => array(), 'publish_flag' => AMQP_NOPARAM); // Create AMQP Connection $amqpConnection = new \AMQPConnection(array('host' => $options['host'], 'port' => $options['port'], 'vhost' => $options['vhost'], 'login' => $options['login'], 'password' => $options['password'])); $amqpConnection->connect(); // Create AMQP Channel $channel = new \AMQPChannel($amqpConnection); // Create exchange $exchange = new \AMQPExchange($channel); // Create queue $queue = new \AMQPQueue($channel); $queue->setName($options['queue_name']); /** @see https://github.com/pdezwart/php-amqp/pull/58 */ $queue->declareQueue(); // Create amqp adapter $adapter = new AmqpAdapter(); $adapter->setRoutingKey($options['queue_name'])->setPublishFlag($options['publish_flag'])->setPublishOptions($options['publish_options'])->setExchange($exchange)->setQueue($queue); /** @var Amqp $amqp */ $amqp = new static(); $amqp->setNotification($notification)->setAdapter($adapter); return $amqp; }
/** * 入RabbitMQ队列 * @param [type] $exName [交换机名] * @param [type] $routingKey [路由名] * @param [type] $value [队列的值] * @param [type] $dbType [数据库类型,默认为mysql] * 按照此规则生成的默认队列名称为 exName_routeKey_dbType;值为value */ public function set($exName, $routingKey, $value, $dbType = 'mysql') { //创建交换机,设置交换机名 $ex = new \AMQPExchange($this->channel); $ex->setName($exName); $ex->setType(AMQP_EX_TYPE_DIRECT); //广播模式 $ex->setFlags(AMQP_DURABLE); //交换器进行持久化,即 RabbitMQ 重启后会自动重建 // $ex->declareExchange(); //设置队列名 $queue = new \AMQPQueue($this->channel); $queue->setName($exName . '_' . $routingKey . '_' . $dbType); $queue->setFlags(AMQP_DURABLE); //队列进行持久化,即 RabbitMQ 重启后会自动重建 $queue->declareQueue(); //交换机和路由绑定到队列 $queue->bind($exName, $routingKey); //入队列 if (is_array($value)) { $value = json_encode($value); } $ex->publish($value, $routingKey, AMQP_NOPARAM, array('delivery_mode' => '2')); }
/** * Connect to queue, see if there's a result waiting for us * Private - to be used internally */ private function getCompleteResult() { if ($this->complete_result) { return $this->complete_result; } $this->connection->connect(); $ch = new AMQPChannel($this->connection); $q = new AMQPQueue($ch); $q->setName($this->task_id); $q->setFlags(AMQP_AUTODELETE); # $q->setArgument('x-expires', 86400000); $q->declareQueue(); try { $q->bind('celeryresults', $this->task_id); } catch (AMQPQueueException $e) { $q->delete(); $this->connection->disconnect(); return false; } $message = $q->get(AMQP_AUTOACK); if (!$message) { $q->delete(); $this->connection->disconnect(); return false; } $this->complete_result = $message; if ($message->getContentType() != 'application/json') { $q->delete(); $this->connection->disconnect(); throw new CeleryException('Response was not encoded using JSON - found ' . $message->getContentType() . ' - check your CELERY_RESULT_SERIALIZER setting!'); } $this->body = json_decode($message->getBody()); $q->delete(); $this->connection->disconnect(); return false; }
include 'web.php'; include 'image_analyzer.php'; include 'storage.php'; /** * Подключаемся к брокеру и точке обмена сообщениями */ $rabbit = new AMQPConnection(array('host' => '127.0.0.1', 'port' => '5672', 'login' => 'guest', 'password' => 'guest')); $rabbit->connect(); $channel = new AMQPChannel($rabbit); $queue = new AMQPExchange($channel); $queue->setName('amq.direct'); /** * Добавляем очередь откуда будем брать страницы */ $q = new AMQPQueue($channel); $q->setName('images_to_scan'); $q->declare(); $q->bind('amq.direct', 'analyze_image'); /** * Обрабатываем пока в очереди не закончатся сообщения */ while (true) { $image = $q->get(); if ($image) { $url = $image->getBody(); echo "Checking: {$url}\n"; $analyzer = new ImageAnalyzer($url); /** * Если картинка еще не была проанализирована, обрабатываем и добавляем в индекс */ $analyzer->analyze();
//Establish connection to AMQP $connection = new AMQPConnection(); $connection->setHost('127.0.0.1'); $connection->setLogin('guest'); $connection->setPassword('guest'); $connection->connect(); //Declare Channel $channel = new AMQPChannel($connection); $routing_key = $severity = isset($argv[1]) && !empty($argv[1]) ? $argv[1] : 'info'; $message = implode(' ', array_slice($argv, 2)); if (empty($message)) { $message = 'Hello World!'; } try { //Declare Exchange $exchange_name = 'direct_logs'; $exchange = new AMQPExchange($channel); $exchange->setType(AMQP_EX_TYPE_DIRECT); $exchange->setName($exchange_name); $exchange->declareExchange(); $queue = new AMQPQueue($channel); $queue->setFlags(AMQP_EXCLUSIVE); $queue->setName('monitor.1'); $queue->declareQueue(); $queue->bind($exchange_name, $routing_key); $exchange->publish($message, $routing_key); echo " [x] Sent {$severity}:{$message}", PHP_EOL; } catch (Exception $ex) { print_r($ex); } $connection->disconnect();