Exemplo n.º 1
0
 public function getEnvelope()
 {
     if (!$this->envelope) {
         $class = $this->envelope_skeleton;
         $this->envelope = new $class($this->original->getExchangeName(), $this->original->getRoutingKey(), $this->original->getDeliveryTag(), $this->original->isRedelivery());
     }
     return $this->envelope;
 }
Exemplo n.º 2
0
 public function consume($payload, AMQPEnvelope $envelope, AMQPQueue $queue)
 {
     if (rand(0, 100) > 95) {
         throw new Exception('some atmospheric disturbances');
     } elseif (rand(0, 100) > 85) {
         throw new Exception('low battery charge');
     } elseif (rand(0, 100) > 75) {
         throw new Exception('low audio quality');
     }
     echo "Received forecast #{$this->count()} from {$this->getRadioStation()} radio station: {$payload}, route key({$envelope->getRoutingKey()})", PHP_EOL;
 }
 /**
  * @test
  */
 public function it_should_reject_a_envelope_when_there_is_a_exception()
 {
     $middleware = new ConsumeMiddleware(false);
     $this->queue->shouldNotReceive('ack')->with('tag');
     $this->queue->shouldReceive('reject')->once()->with('tag', AMQP_NOPARAM);
     $this->envelope->shouldReceive('getDeliveryTag')->withNoArgs()->andReturn('tag');
     $this->setExpectedException(\RuntimeException::class, 'The queue should reject the message now');
     $middleware->execute($this->command, function () {
         throw new \RuntimeException('The queue should reject the message now');
     });
 }
Exemplo n.º 4
0
 /**
  * @param \AMQPEnvelope $envelope
  * @param \AMQPQueue $queue
  * @param string $m
  */
 public function publish($envelope, $queue, $m)
 {
     if ($m instanceof AmqpResp) {
         $m = Json::encode($m->getData());
     } elseif (is_object($m) || is_array($m)) {
         $m = Json::encode($m);
     }
     $chanel = $this->getChanel();
     // Точка доступа
     // Точка обмена
     $exchange = new \AMQPExchange($chanel);
     $exchange->setFlags(AMQP_AUTODELETE | AMQP_DURABLE);
     $attributes = array('correlation_id' => $envelope->getCorrelationId());
     $routingKey = $envelope->getReplyTo();
     if ($exchange->publish($m, $routingKey, AMQP_NOPARAM, $attributes)) {
         $queue->ack($envelope->getDeliveryTag());
     }
 }
Exemplo n.º 5
0
 public function extractMessageFromAMQP(\AMQPEnvelope $env, \AMQPQueue $q)
 {
     $this->lastEnvelope = $env;
     $message = @unserialize($env->getBody());
     if (!is_object($message)) {
         /* Since ext/amqp 1.0.5, exceptions may be thrown from the callback
          * though we haven't patched that yet */
         @trigger_error(sprintf('Given message should be an object, "%s" given.', gettype($message)), E_USER_WARNING);
         /* Return from the callback, this will return to extractMessage() */
         return false;
     }
     if (!$message instanceof Message) {
         /* Since ext/amqp 1.0.5, exceptions may be thrown from the callback
          * though we haven't patched that yet */
         @trigger_error(sprintf('Unexpected message, should be a Capl\\AMQP\\Message\\Message, "%s" given', get_class($message)), E_USER_WARNING);
         /* Return from the callback, this will return to extractMessage() */
         return false;
     }
     $message->setAMQPEnvelope($env);
     $this->messageProcessor->processMessage($message);
 }
Exemplo n.º 6
0
 public function retrieveHeaders(\AMQPEnvelope $envelope)
 {
     $headers = $envelope->getHeaders();
     if ($envelope->getReplyTo() !== '' && !isset($headers[HeaderTypeEnum::REPLY_TO_ADDRESS])) {
         $headers[HeaderTypeEnum::REPLY_TO_ADDRESS] = $envelope->getReplyTo();
     }
     if ($envelope->getCorrelationId() !== '') {
         $headers[HeaderTypeEnum::CORRELATION_ID] = $envelope->getCorrelationId();
     }
     if ($envelope->getType() !== '' && !isset($headers[HeaderTypeEnum::ENCLOSED_CLASS])) {
         $headers[HeaderTypeEnum::ENCLOSED_CLASS] = $envelope->getType();
     }
     return $headers;
 }
Exemplo n.º 7
0
 public static function castEnvelope(\AMQPEnvelope $c, array $a, Stub $stub, $isNested, $filter = 0)
 {
     $prefix = Caster::PREFIX_VIRTUAL;
     if (!($filter & Caster::EXCLUDE_VERBOSE)) {
         $a += array($prefix . 'body' => $c->getBody());
     }
     $a += array($prefix . 'routingKey' => $c->getRoutingKey(), $prefix . 'deliveryTag' => $c->getDeliveryTag(), $prefix . 'deliveryMode' => new ConstStub($c->getDeliveryMode() . (2 === $c->getDeliveryMode() ? ' (persistent)' : ' (non-persistent)'), $c->getDeliveryMode()), $prefix . 'exchangeName' => $c->getExchangeName(), $prefix . 'isRedelivery' => $c->isRedelivery(), $prefix . 'contentType' => $c->getContentType(), $prefix . 'contentEncoding' => $c->getContentEncoding(), $prefix . 'type' => $c->getType(), $prefix . 'timestamp' => $c->getTimestamp(), $prefix . 'priority' => $c->getPriority(), $prefix . 'expiration' => $c->getExpiration(), $prefix . 'userId' => $c->getUserId(), $prefix . 'appId' => $c->getAppId(), $prefix . 'messageId' => $c->getMessageId(), $prefix . 'replyTo' => $c->getReplyTo(), $prefix . 'correlationId' => $c->getCorrelationId(), $prefix . 'headers' => $c->getHeaders());
     return $a;
 }
Exemplo n.º 8
0
 /**
  * Convert AMQP message to internal message format
  *
  * @param \AMQPEnvelope $envelope
  *
  * @return BaseMessage
  */
 public static function convert(\AMQPEnvelope $envelope)
 {
     $message = new BaseMessage();
     $message->setPayload($envelope->getBody())->setDeliveryMode($envelope->getDeliveryMode())->setHeaders($envelope->getHeaders())->setProperties(['content_type' => $envelope->getContentType(), 'content_encoding' => $envelope->getContentEncoding(), 'app_id' => $envelope->getAppId(), 'correlation_id' => $envelope->getCorrelationId(), 'delivery_tag' => $envelope->getDeliveryTag(), 'message_id' => $envelope->getMessageId(), 'priority' => $envelope->getPriority(), 'reply_to' => $envelope->getReplyTo(), 'routing_key' => $envelope->getRoutingKey(), 'exchange_name' => $envelope->getExchangeName(), 'timestamp' => $envelope->getTimeStamp(), 'type' => $envelope->getType(), 'user_id' => $envelope->getUserId()]);
     return $message;
 }
 /**
  * @param \AMQPEnvelope $message
  * @return mixed|string
  * @throws \Exception
  */
 protected function unpackMessage(\AMQPEnvelope $message)
 {
     switch ($message->getContentType()) {
         case 'text/plain':
             return $message->getBody();
         case 'serialized/array':
             return unserialize($message->getBody());
         default:
             throw new \Exception('Unsupported message content type ' . $message->getContentType());
     }
 }
Exemplo n.º 10
0
 /**
  * @param \AMQPEnvelope $envelope
  * @return string
  */
 public static function envelopeToString(\AMQPEnvelope $envelope)
 {
     $m = '';
     $m .= 'AppId: ' . $envelope->getAppId() . "\n";
     $m .= 'Body: ' . $envelope->getBody() . "\n";
     $m .= 'ContentEncoding: ' . $envelope->getContentEncoding() . "\n";
     $m .= 'ContentType: ' . $envelope->getContentType() . "\n";
     $m .= 'CorrelationId: ' . $envelope->getCorrelationId() . "\n";
     $m .= 'DeliveryTag: ' . $envelope->getDeliveryTag() . "\n";
     $m .= 'ExchangeName: ' . $envelope->getExchangeName() . "\n";
     $m .= 'Expiration: ' . $envelope->getExpiration() . "\n";
     $m .= 'Headers: ' . json_encode($envelope->getHeaders()) . "\n";
     $m .= 'MessageId: ' . $envelope->getMessageId() . "\n";
     $m .= 'Priority: ' . $envelope->getPriority() . "\n";
     $m .= 'ReplyTo: ' . $envelope->getReplyTo() . "\n";
     $m .= 'RoutingKey: ' . $envelope->getRoutingKey() . "\n";
     $m .= 'TimeStamp: ' . $envelope->getTimeStamp() . "\n";
     $m .= 'Type: ' . $envelope->getType() . "\n";
     $m .= 'UserId: ' . $envelope->getUserId() . "\n";
     $m .= 'isRedelivery: ' . $envelope->isRedelivery() . "\n";
     $m .= "\n";
     return $m;
 }
Exemplo n.º 11
0
 /**
  * @param \AMQPEnvelope                    $message
  * @param MessageEncodeDecodeStrategy|null $decodeStrategy
  *
  * @return static
  * @throws \yii\base\InvalidConfigException
  */
 public static function createFromRaw(\AMQPEnvelope $message, $decodeStrategy = null)
 {
     return \Yii::createObject(['class' => static::class, 'body' => $message->getBody(), 'routingKey' => $message->getRoutingKey(), 'deliveryTag' => $message->getDeliveryTag(), 'deliveryMode' => $message->getDeliveryMode(), 'exchangeName' => $message->getExchangeName(), 'redelivery' => $message->isRedelivery(), 'contentType' => $message->getContentType(), 'contentEncoding' => $message->getContentEncoding(), 'type' => $message->getType(), 'timestamp' => $message->getTimeStamp(), 'priority' => $message->getPriority(), 'expiration' => $message->getExpiration(), 'userId' => $message->getUserId(), 'appId' => $message->getAppId(), 'messageId' => $message->getMessageId(), 'replyTo' => $message->getReplyTo(), 'correlationId' => $message->getCorrelationId(), 'headers' => $message->getHeaders(), 'decodeStrategy' => $decodeStrategy]);
 }
 /**
  * @param AMQPEnvelope $incoming
  * @return AMQPIncomingMessage
  */
 public static function convert(AMQPEnvelope $incoming)
 {
     $data = array(AMQPIncomingMessage::APP_ID => $incoming->getAppId(), AMQPIncomingMessage::BODY => $incoming->getBody(), AMQPIncomingMessage::CONTENT_ENCODING => $incoming->getContentEncoding(), AMQPIncomingMessage::CONTENT_TYPE => $incoming->getContentType(), AMQPIncomingMessage::CORRELATION_ID => $incoming->getCorrelationId(), AMQPIncomingMessage::DELIVERY_TAG => $incoming->getDeliveryTag(), AMQPIncomingMessage::DELIVERY_MODE => $incoming->getDeliveryMode(), AMQPIncomingMessage::EXCHANGE => $incoming->getExchangeName(), AMQPIncomingMessage::EXPIRATION => $incoming->getExpiration(), AMQPIncomingMessage::MESSAGE_ID => $incoming->getMessageId(), AMQPIncomingMessage::PRIORITY => $incoming->getPriority(), AMQPIncomingMessage::REPLY_TO => $incoming->getReplyTo(), AMQPIncomingMessage::REDELIVERED => $incoming->isRedelivery(), AMQPIncomingMessage::PRIORITY => $incoming->getPriority(), AMQPIncomingMessage::ROUTING_KEY => $incoming->getRoutingKey(), AMQPIncomingMessage::TIMESTAMP => $incoming->getTimeStamp(), AMQPIncomingMessage::TYPE => $incoming->getType(), AMQPIncomingMessage::USER_ID => $incoming->getUserId());
     return AMQPIncomingMessage::spawn($data);
 }
Exemplo n.º 13
0
 public function process(\AMQPEnvelope $message)
 {
     echo 'FOO:' . $message->getBody() . "\n";
     return "test-response";
 }
Exemplo n.º 14
0
 public function execute(\AMQPEnvelope $envelope, \AMQPQueue $queue)
 {
     echo 'Receive `' . $envelope->getBody() . '` from queue `' . $queue->getName() . '`' . PHP_EOL;
 }
 function callback(AMQPEnvelope $message, AMQPQueue $q)
 {
     //say that message received
     $q->ack($message->getDeliveryTag());
 }
Exemplo n.º 16
0
 /**
  * Nacks the message
  *
  * @param AMQPEnvelope $envelope
  *
  * @return void
  */
 public function nack(AMQPEnvelope $envelope)
 {
     $this->_queues[$this->_consumerQueue]->nack($envelope->getDeliveryTag());
 }
Exemplo n.º 17
0
 /**
  * @inheritdoc
  */
 public function isRedelivery()
 {
     return $this->delegate->isRedelivery();
 }
Exemplo n.º 18
0
 private function setupConsume($flags, $consumer_tag = null)
 {
     $auto_ack = boolval($flags & AMQP_AUTOACK);
     if ($consumer_tag === null) {
         $consumer_tag = '';
     }
     //Man-in-the-middle callback to transform response to an envelope.
     //AMQPProtocolChannelException
     $queue = $this;
     list($this->consumer_tag) = $this->channel->_getChannel()->basic_consume($this->name, $consumer_tag, $no_local = false, $auto_ack, $exclusive = false, $nowait = false, function (AMQPMessage $message) use($queue) {
         $queue->last_envelope = AMQPEnvelope::fromAMQPMessage($message);
     });
 }
Exemplo n.º 19
0
 public function process(\AMQPEnvelope $message)
 {
     echo 'Date time is: ' . $message->getBody() . PHP_EOL;
 }
Exemplo n.º 20
0
 /**
  * 收到一条消息后的回调函数
  * @param \AMQPEnvelope $envelope
  * @param \AMQPQueue $queue
  * @return boolean
  */
 public function myCallback($envelope, $queue)
 {
     $this->_msgArray[] = $envelope->getBody();
     if (SKY_DEBUG) {
         if ($time = $envelope->getTimeStamp()) {
             $this->_totalTime += floor(microtime(true) * 1000) - $time;
         }
     }
     $isTimeout = $this->timeout($this->_beginTime);
     // 		$queue->ack($envelope->getDeliveryTag()); //手动发送ACK应答
     if (++$this->_counter >= $this->maxExecCount || $isTimeout) {
         if ($isTimeout) {
             echo "didn't get enough messages, but the round has timeout.\n";
         } else {
             echo "we got total {$this->maxExecCount} messages, begin process..\n";
         }
         return FALSE;
         //处理n个消息或超时后退出
     }
 }
Exemplo n.º 21
0
 public function fromEnvelope(\AMQPEnvelope $envelope)
 {
     $this->setAppId($envelope->getAppId());
     $this->setBody($envelope->getBody());
     $this->setContentEncoding($envelope->getContentEncoding());
     $this->setContentType($envelope->getContentType());
     $this->setCorrelationId($envelope->getCorrelationId());
     $this->setDeliveryMode($envelope->getDeliveryMode());
     $this->setDeliveryTag($envelope->getDeliveryTag());
     $this->setExchangeName($envelope->getExchangeName());
     $this->setExpiration($envelope->getExpiration());
     $this->setHeaders($envelope->getHeaders());
     $this->setMessageId($envelope->getMessageId());
     $this->setPriority($envelope->getPriority());
     $this->setReplyTo($envelope->getReplyTo());
     $this->setRoutingKey($envelope->getRoutingKey());
     $this->setTimeStamp($envelope->getTimeStamp());
     $this->setType($envelope->getType());
     $this->setUserId($envelope->getUserId());
     $this->setRedelivery($envelope->isRedelivery());
     return $this;
 }
Exemplo n.º 22
0
 /**
  * Implements all the needed behaviors for processing messages in case of errors
  * This method will nack all the provious messages or ack all the previous messages in the case of a failed message
  * The results can be surprising.
  *
  * @param AMQPEnvelope $message The message to be processed
  * @param bool|int     $result  The reply from the processor
  *
  * @return void
  */
 protected function processError(\AMQPEnvelope $message, $result)
 {
     if (isset($this->configuration['onProcessError'])) {
         $stopOnError = $this->configuration['onProcessError'];
         // set up a sensible default
         $action = 'error';
         switch ($result) {
             case Processor::CRIT_INTERNAL_SERVER_ERROR:
                 if (isset($stopOnError['crit_internal_server_error'])) {
                     $action = $stopOnError['crit_internal_server_error'];
                 }
                 break;
             case Processor::CRIT_NOT_IMPLEMENTED:
                 if (isset($stopOnError['crit_not_implemented'])) {
                     $action = $stopOnError['crit_not_implemented'];
                 }
                 break;
             case Processor::ERR_BAD_REQUEST:
                 if (isset($stopOnError['err_bad_request'])) {
                     $action = $stopOnError['err_bad_request'];
                 }
                 break;
             case Processor::ERR_NOT_FOUND:
                 if (isset($stopOnError['err_not_found'])) {
                     $action = $stopOnError['err_not_found'];
                 }
                 break;
         }
         switch ($action) {
             case 'error':
                 $this->queue->nack($message->getDeliveryTag(), AMQP_MULTIPLE);
                 $this->nackCounter = 0;
                 break;
             case 'requeue':
                 $this->queue->nack($message->getDeliveryTag(), AMQP_REQUEUE | AMQP_MULTIPLE);
                 $this->nackCounter = 0;
                 break;
             case 'stop':
                 $this->queue->nack($message->getDeliveryTag(), AMQP_MULTIPLE);
                 exit(1);
             case 'continue':
             default:
                 $this->queue->ack($message->getDeliveryTag(), AMQP_MULTIPLE);
                 // reset the nack counter
                 $this->nackCounter = 0;
                 break;
         }
     } else {
         $this->queue->nack($message->getDeliveryTag());
     }
 }
Exemplo n.º 23
0
 /**
  * @param \AMQPEnvelope $input
  */
 protected function consume($input)
 {
     pcntl_signal_dispatch();
     static $doublesCheck = true, $doubles = [], $cleanerCount = 0, $cleanerLimit = 10000;
     if ($doublesCheck === null) {
         $doublesCheck = $this->config['doubles_check']['enabled'];
         $cleanerLimit = $this->config['doubles_check']['limit'];
     }
     static $hasOutputQueue;
     if ($hasOutputQueue === null) {
         $hasOutputQueue = isset($this->config['output-queue'], $this->config['output-queue']['enabled']) && $this->config['output-queue']['enabled'];
     }
     $post = json_decode($input->getBody(), true);
     if ($hasOutputQueue) {
         static $outputQueue, $queue;
         if ($outputQueue === null || $queue === null) {
             $outputQueue = $this->config['output-queue'];
             $queue = rabbit::factory($outputQueue['section']);
         }
         $queue->sendToBackground($outputQueue['queueName'], $post);
     }
     $this->pause && usleep($this->pause);
     if ($doublesCheck) {
         if (isset($post['_hash']) && !isset($doubles[$post['_hash']])) {
             self::$queue[] = $post;
             $this->addStatsItem('processed');
             $doubles[$post['_hash']] = true;
             if (++$cleanerCount > $cleanerLimit) {
                 $doubles = array_slice($doubles, (int) ($cleanerLimit / 4));
                 $cleanerCount = count($doubles);
             }
         }
     } else {
         self::$queue[] = $post;
         $this->addStatsItem('processed');
     }
     $time = time();
     static $nextPauseUpdate = 0;
     if ($nextPauseUpdate < $time) {
         $this->updatePause();
         $nextPauseUpdate = $time + 1;
     }
 }