/**
  * 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;
 }
Пример #2
0
 public function Run()
 {
     // Declare a new exchange
     $ex = new AMQPExchange($this->cnn);
     $ex->declare('game', AMQP_EX_TYPE_FANOUT);
     // Create a new queue
     $q1 = new AMQPQueue($this->cnn);
     $q1->declare('queue1');
     $q2 = new AMQPQueue($this->cnn);
     $q2->declare('queue2');
     // Bind it on the exchange to routing.key
     //$ex->bind('queue1', 'broadcast=true,target=queue1,x-match=any');
     $ex->bind('queue1', '');
     $ex->bind('queue2', '');
     $msgBody = 'hello';
     // Publish a message to the exchange with a routing key
     $ex->publish($msgBody, 'foo');
     // Read from the queue
     $msg = $q1->consume();
     $this->AssertEquals(count($msg), 1);
     $this->AssertEquals($msg[0]['message_body'], $msgBody, 'message not equal');
     // Read from the queue
     $msg = $q2->consume();
     $this->AssertEquals(count($msg), 1);
     $this->AssertEquals($msg[0]['message_body'], $msgBody, 'message not equal');
     $this->AddMessage(var_export($msg[0], true));
 }
Пример #3
0
 /**
  * On dispatch event listener - called on any event
  * AMQP_MANDATORY: When publishing a message, the message must be routed to a valid queue. If it is not, an error will be returned.
  *  if the client publishes a message with the "mandatory" flag set to an exchange of "direct" type which is not bound to a queue.
  * AMQP_IMMEDIATE: When publishing a message, mark this message for immediate processing by the broker.
  *      REMOVED from rabbitmq > 3-0 http://www.rabbitmq.com/blog/2012/11/19/breaking-things-with-rabbitmq-3-0
  * @param Event $event
  * @param string $eventName
  * @return void
  */
 public function publish(Amqp\PublishEvent $event, $eventName, \AMQPExchange $exchange)
 {
     $success = $exchange->publish($event->getBody(), $eventName, $event->getFlags(), $event->jsonSerialize());
     if ($this->stopPropagation) {
         $event->stopPropagation();
     }
 }
Пример #4
0
 public function call($value)
 {
     $this->response = NULL;
     $this->corrId = uniqid();
     try {
         //Declare an nonymous channel
         $this->queue = new AMQPQueue($this->channel);
         $this->queue->setFlags(AMQP_EXCLUSIVE);
         $this->queue->declareQueue();
         $this->callbackQueueName = $this->queue->getName();
         //Set Publish Attributes
         $attributes = ['correlation_id' => $this->corrId, 'reply_to' => $this->callbackQueueName];
         $this->exchange->publish($value, $this->rpcQueue, AMQP_NOPARAM, $attributes);
         $callback = function (AMQPEnvelope $message, AMQPQueue $q) {
             if ($message->getCorrelationId() == $this->corrId) {
                 //echo sprintf("CorrelationID: %s",$message->getCorrelationId()), PHP_EOL;
                 //echo sprintf("Response: %s",$message->getBody()), PHP_EOL;
                 $this->response = $message->getBody();
                 $q->nack($message->getDeliveryTag());
                 return false;
             }
         };
         $this->queue->consume($callback);
         //Return RPC Results
         return $this->response;
     } catch (AMQPQueueException $ex) {
         print_r($ex);
     } catch (Exception $ex) {
         print_r($ex);
     }
 }
 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);
 }
Пример #6
0
 public function send($msg)
 {
     $ex = new \AMQPExchange($this->amqpChannel);
     $ex->setName($this->name);
     $ex->publish($msg);
     return $this;
 }
Пример #7
0
 /**
  * Bind queue to exchange using dispatcher event names as routing keys
  *
  * @return void
  * @throws AMQPExchangeException
  */
 public function bind(\AMQPQueue $queue, \AMQPExchange $exchange)
 {
     $events = preg_grep($this->pattern, array_keys($this->getDispatcher()->getListeners()));
     foreach ($events as $eventName) {
         $queue->bind($exchange->getName(), $eventName);
     }
     $this->dispatcher->dispatch(static::BIND_EVENT, new SymfonyEvent($events, ["pattern" => $this->pattern, "exchange" => $exchange->getName(), "queue" => $queue->getName()]));
 }
Пример #8
0
 /**
  * Publish the message to AMQP exchange
  *
  * @param Message $message
  * @param \AMQPExchange $exchange
  * @return bool
  * @throws \AMQPException
  */
 protected function publishToExchange(Message $message, \AMQPExchange $exchange)
 {
     $isPublished = $exchange->publish($message->getMessage(), $message->getRoutingKey(), $message->getFlags(), $message->getAttributes());
     if (!$isPublished) {
         throw FailedToPublishException::fromMessage($message);
     }
     return $isPublished;
 }
Пример #9
0
 /**
  * 广播形式写入队列
  *
  * @Author   tianyunzi
  * @DateTime 2015-08-19T18:44:42+0800
  */
 public function setBroadcast($exName, $routingKey, $value)
 {
     //创建交换机
     $ex = new \AMQPExchange($this->channel);
     $ex->setName($exName);
     //入队列
     $ex->publish($value, $routingKey, AMQP_NOPARAM, array('delivery_mode' => '2'));
 }
Пример #10
0
 /**
  * Post a task to exchange specified in $details
  * @param AMQPConnection $connection Connection object
  * @param array $details Array of connection details
  * @param string $task JSON-encoded task
  * @param array $params AMQP message parameters
  */
 function PostToExchange($connection, $details, $task, $params)
 {
     $ch = $connection->channel;
     $xchg = new AMQPExchange($ch);
     $xchg->setName($details['exchange']);
     $success = $xchg->publish($task, $details['binding'], 0, $params);
     return $success;
 }
Пример #11
0
 /**
  * @param Request $rpcRequest
  *
  * @return Response|null
  */
 protected function sendRequest(Request $rpcRequest)
 {
     $message = $this->serializer->serialize($rpcRequest, $this->protocol, ['encoding' => $this->encoding]);
     $routingKey = $this->routingKey;
     $flags = $this->flags;
     $attributes = ['content_type' => 'application/' . $this->encoding, 'rpc_type' => $this->protocol];
     $this->exchange->publish($message, $routingKey, $flags, $attributes);
 }
 /**
  * {@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;
         };
     };
 }
 /**
  * Publishes a message
  *
  * @param AMQPMessage $msg
  * @param string $exchange
  * @param string $routing_key
  * @param bool $mandatory
  * @param bool $immediate
  * @param null $ticket
  */
 public function basic_publish($msg, $exchange = '', $routing_key = '', $mandatory = false, $immediate = false, $ticket = null)
 {
     $flags = AMQP_NOPARAM;
     $flags += $mandatory ? AMQP_MANDATORY : 0;
     $flags += $immediate ? AMQP_IMMEDIATE : 0;
     $xchange = new \AMQPExchange($this->channel);
     $xchange->setName($exchange);
     $xchange->publish($msg->body, $routing_key, $flags, $msg->get_properties());
 }
 /**
  * @param string $name
  *
  * @return \AMQPExchange
  */
 protected function getExchange($name)
 {
     if (!isset($this->exchanges[$name])) {
         $exchange = new \AMQPExchange($this->getChannel());
         $exchange->setName($name);
         $this->exchanges[$name] = $exchange;
     }
     return $this->exchanges[$name];
 }
 protected function getAMQPExchange()
 {
     $connection = new \AMQPConnection(array('vhost' => 'swarrot'));
     $connection->connect();
     $channel = new \AMQPChannel($connection);
     $exchange = new \AMQPExchange($channel);
     $exchange->setName('exchange');
     return $exchange;
 }
Пример #16
0
 /**
  * Attempts to reconnect on a dead connection
  * Usable for long running processes, where the stale connections get collected
  * after some time
  *
  * @return void
  */
 protected function reconnect()
 {
     $connection = $this->exchange->getConnection();
     $channel = $this->exchange->getChannel();
     $connection->reconnect();
     // since the channel is also dead, need to somehow revive it. This can be
     // done only by calling the constructor of the channel
     $channel->__construct($connection);
 }
Пример #17
0
 /**
  * @inheritdoc
  */
 public function createExchange(ChannelInterface $channel, $name, $type = ExchangeInterface::TYPE_DIRECT, $flags = null, array $args = [])
 {
     $delegate = new \AMQPExchange($channel->getDelegate());
     $delegate->setName($name);
     $delegate->setType($type);
     $delegate->setFlags(Exchange::convertToDelegateFlags($flags));
     $delegate->setArguments($args);
     return new Exchange($delegate, $channel);
 }
Пример #18
0
 public static function resend($message, $routekey, $exchange = 'momo_nd', $appid = 0, $uid = 0)
 {
     try {
         $obj_conn = new AMQPConnect(Kohana::config('uap.rabbitmq'));
         $obj_exchange = new AMQPExchange($obj_conn, $exchange);
         $obj_exchange->publish($message, $routekey, AMQP_MANDATORY, array('app_id' => "{$appid}", 'user_id' => "{$uid}"));
     } catch (Exception $e) {
         Kohana::log('error', "再次发送消息失败 message = " . $message . "\n" . $e->getTraceAsString());
     }
 }
Пример #19
0
 /**
  * Testing send message without errors
  *
  * @dataProvider providerAddMessageParameters
  */
 public function testAddMessage($routingKey, $publishFlag, $publishParameters)
 {
     $message = new Message();
     $message->setDeviceToken(str_repeat('af', 32))->setBody('Foo bar');
     $messageSerialized = serialize($message);
     $this->exchange->expects($this->once())->method('publish')->with($messageSerialized, $routingKey, $publishFlag, $publishParameters)->will($this->returnValue(true));
     $adapter = new AmqpAdapter();
     $adapter->setExchange($this->exchange)->setRoutingKey($routingKey)->setPublishOptions($publishParameters)->setPublishFlag($publishFlag);
     $adapter->addMessage($message);
 }
Пример #20
0
 protected function publishToExchange(Message $message, \AMQPExchange $exchange)
 {
     $attributes = (array) $message->getAttributes();
     $attributes['correlation_id'] = $this->correlationId;
     $isPublished = $exchange->publish($message->getMessage(), $this->routingKey, $message->getFlags(), $attributes);
     if (!$isPublished) {
         throw FailedToPublishException::fromMessage($message);
     }
     return $isPublished;
 }
Пример #21
0
 /**
  * @param \AMQPExchange $exchange
  * @return \AMQPQueue
  */
 protected function declareResponseQueue(\AMQPExchange $exchange)
 {
     $queue = new \AMQPQueue($exchange->getChannel());
     $queue->setFlags(AMQP_EXCLUSIVE);
     if ($this->queueTimeout !== null) {
         $queue->setArgument("x-expires", $this->queueTimeout);
     }
     $queue->declareQueue();
     return $queue;
 }
Пример #22
0
 /**
  * Responds to an rpc call. The response is broadcasted on the default exchange of the incoming queue, in order to
  * avoid publishing on the wrong exchange and never receiving the answer
  *
  * @param AMQPEnvelope $message  The message to be processed
  * @param bool         $response The response that was retrieved from the processor
  *
  * @throws Exception If the response cannot be republished
  */
 protected function publishResponse(AMQPEnvelope $message, $response = false)
 {
     // get the queue's channel
     $channel = $this->queue->getChannel();
     $exchange = new \AMQPExchange($channel);
     // publish on exchange the response message
     $result = $exchange->publish($response, $message->getReplyTo());
     if ($result === false) {
         throw new Exception('Cannot publish response on reply queue!');
     }
 }
Пример #23
0
 /**
  * {@inheritdoc}
  */
 public function publish($message, $routingKey = '', array $properties = array())
 {
     if (!isset($properties['timestamp'])) {
         $properties['timestamp'] = microtime(true);
     }
     // make messages durable by default
     if (!isset($properties['delivery_mode'])) {
         $properties['delivery_mode'] = 2;
     }
     $response = $this->exchange->publish($message, $routingKey, AMQP_NOPARAM, $properties);
     return $response;
 }
Пример #24
0
 /**
  * getExchange
  *
  * @param string $name
  * @param string $connection
  *
  * @return \AMQPExchange
  */
 public function getExchange($name, $connection)
 {
     if (!isset($this->exchanges[$connection][$name])) {
         if (!isset($this->exchanges[$connection])) {
             $this->exchanges[$connection] = array();
         }
         $exchange = new \AMQPExchange($this->getChannel($connection));
         $exchange->setName($name);
         $this->exchanges[$connection][$name] = $exchange;
     }
     return $this->exchanges[$connection][$name];
 }
Пример #25
0
 /**
  * Sends a message to the specified exchange.
  * ATM, exchange must already exists on the broker.
  *
  * @param string $msg
  * @param string $exchangeName
  * @param string $routingKey
  * @param boolean $mandatory
  * @param boolean $immediate
  * @param array $attributes
  * @return boolean
  * @see http://www.php.net/manual/en/amqpexchange.publish.php
  */
 public function send($msg, $exchangeName = '', $routingKey = '', $mandatory = false, $immediate = false, array $attributes = array())
 {
     $exchange = new AMQPExchange($this->_channel);
     $exchange->setName($exchangeName);
     $flags = AMQP_NOPARAM;
     if ($mandatory) {
         $flags |= AMQP_MANDATORY;
     }
     if ($immediate) {
         $flags |= AMQP_IMMEDIATE;
     }
     return $exchange->publish((string) $msg, (string) $routingKey, $flags, $attributes);
 }
Пример #26
0
 /**
  * Enqueues given $message
  *
  * @throws FailedEnqueueException
  */
 public function enqueue(Message $message, $timeout = 0, callable $onTimeout = null)
 {
     if ($message instanceof Delayable) {
         if ($message->delayedUntil() < new \DateTime('now')) {
             throw new \OutOfBoundsException('Cannot enqueue messages in the past');
             // do something
         }
     }
     $body = $message->getBody();
     $route = $message->getRoutingKey();
     $props = $message->getHeaders();
     return $this->exchange->publish($body, $route, $flags, $props);
 }
Пример #27
0
 public function pushMessage($queueName, array $message)
 {
     try {
         $queue = new AMQPQueue($this->channel);
         $queue->setName($queueName);
         $queue->setFlags(AMQP_DURABLE);
         $queue->declareQueue();
     } catch (Exception $ex) {
         $this->standart_ctrl->error('500', 'AMQ channel unreachable');
     }
     $message = json_encode($message);
     $exchange = new AMQPExchange($this->channel);
     $exchange->publish($message, $queueName);
 }
 public function Run()
 {
     // Declare a new exchange
     $ex = new AMQPExchange($this->cnn);
     $ex->declare('game', AMQP_EX_TYPE_TOPIC);
     // Create a new queue
     $q1 = new AMQPQueue($this->cnn);
     $q1->declare('queue1');
     $q1->purge('queue1');
     $q2 = new AMQPQueue($this->cnn);
     $q2->declare('queue2');
     $q1->purge('queue2');
     $q3 = new AMQPQueue($this->cnn);
     $q3->declare('queue3');
     $q3->purge('queue3');
     $options = array('min' => 0, 'max' => 10, 'ack' => true);
     // Bind it on the exchange to routing.key
     $ex->bind('queue1', 'game1.#');
     $ex->bind('queue2', 'game1.#');
     $ex->bind('queue3', 'game1.#');
     $ex->bind('queue3', 'queue3.#');
     $msgbody1 = 'hello';
     // Publish a message to the exchange with a routing key
     $result = $ex->publish($msgbody1, 'game1.msg');
     $this->AssertEquals($result, TRUE, 'publish message failed');
     $msgbody2 = 'world';
     // Publish a message to the exchange with a routing key
     $result = $ex->publish($msgbody2, 'game1.msg');
     $this->AssertEquals($result, TRUE, 'publish message failed');
     $msgbody3 = 'hello player3';
     // Publish a message to the exchange with a routing key
     $result = $ex->publish($msgbody3, 'queue3.command');
     $this->AssertEquals($result, TRUE, 'publish message failed');
     // Read from the queue
     $msg = $q1->consume($options);
     $this->AddMessage(var_export($msg, true));
     $this->AssertEquals(count($msg), 2);
     $this->AssertEquals($msg[0]['message_body'], $msgbody1, 'message not equal');
     $this->AssertEquals($msg[1]['message_body'], $msgbody2, 'message not equal');
     // Read from the queue
     $msg = $q2->consume($options);
     $this->AssertEquals(count($msg), 2);
     $this->AssertEquals($msg[0]['message_body'], $msgbody1, 'message not equal');
     $this->AssertEquals($msg[1]['message_body'], $msgbody2, 'message not equal');
     // Read from the queue
     $msg = $q3->consume($options);
     $this->AddMessage(var_export($msg, true));
     $this->AssertEquals(count($msg), 3);
     $this->AssertEquals($msg[0]['message_body'], $msgbody1, 'message not equal');
     $this->AssertEquals($msg[1]['message_body'], $msgbody2, 'message not equal');
     $this->AssertEquals($msg[2]['message_body'], $msgbody3, 'message not equal');
     $msg = $q3->consume($options);
     $this->AssertEquals(count($msg), 0);
 }
Пример #29
0
 public function delete()
 {
     if ($this->is_loaded == false) {
         return false;
     }
     try {
         $msg = $this->build_delete();
         $con = MPF_AMQP_Factory::get_instance()->get_connection();
         $ex = new AMQPExchange($con, self::get_exchange());
         $ex->publish($msg, self::get_routing());
     } catch (Exception $e) {
         MPF::get_instance()->get_debugger()->debug('AMPQ: Can not be published - ' . $e->getMessage());
     }
     return true;
 }
Пример #30
0
 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];
 }