Publish a message to the exchange represented by the AMQPExchange object.
public publish ( string $message, string $routing_key = null, integer $flags = AMQP_NOPARAM, array $attributes = [] ) : boolean | ||
$message | string | The message to publish. |
$routing_key | string | The optional routing key to which to publish to. |
$flags | integer | One or more of AMQP_MANDATORY and AMQP_IMMEDIATE. |
$attributes | array | One of content_type, content_encoding, message_id, user_id, app_id, delivery_mode, priority, timestamp, expiration, type or reply_to, headers. |
리턴 | boolean | TRUE on success or FALSE on failure. |
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); } }
/** * @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); }
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); }
/** * {@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; }
/** * 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); }
public function Run() { // Declare a new exchange $ex = new AMQPExchange($this->cnn); $ex->declare('game', AMQP_EX_TYPE_HEADER); // 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', 'broadcast=1,target=1,x-match=any'); $ex->bind('queue2', 'broadcast=1,target=2,x-match=any'); $ex->bind('queue3', 'broadcast=1,target=3,x-match=any'); $msgbody1 = 'hello'; // Publish a message to the exchange with a routing key $result = $ex->publish($msgbody1, NULL, AMQP_IMMEDIATE, array('headers' => array('broadcast' => 1))); $this->AssertEquals($result, TRUE, 'publish message failed'); $msgbody2 = 'world'; // Publish a message to the exchange with a routing key $result = $ex->publish($msgbody2, NULL, AMQP_IMMEDIATE, array('headers' => array('broadcast' => 1))); $this->AssertEquals($result, TRUE, 'publish message failed'); $msgbody3 = 'queue3'; // Publish a message to the exchange with a routing key $result = $ex->publish($msgbody1, NULL, AMQP_IMMEDIATE, array('headers' => array('target' => 3))); $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->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'); }
/** * Publish a message to an exchange. * * Publish a message to the exchange represented by the AMQPExchange object. * * @param string $message The message to publish. * @param string $routingKey The optional routing key to which to publish to. * @param integer $flags One or more of AMQP_MANDATORY and AMQP_IMMEDIATE. * @param array $attributes One of content_type, content_encoding, * message_id, user_id, app_id, delivery_mode, * priority, timestamp, expiration, type * or reply_to, headers. * * @throws \AMQPExchangeException On failure. * @throws \AMQPChannelException If the channel is not open. * @throws \AMQPConnectionException If the connection to the broker was lost. */ public function publish($message, $routingKey = null, $flags = AMQP_NOPARAM, array $attributes = []) { if (!$this->exchangeDeclared) { $this->exchangeDeclare(); } $this->exchange->publish($message, $routingKey, $flags, $attributes); }
/** * 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(); } }
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)); }
/** * 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; }
public function send($msg) { $ex = new \AMQPExchange($this->amqpChannel); $ex->setName($this->name); $ex->publish($msg); return $this; }
/** * 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; }
/** * @param mixed $message * @param string $routingKey * @param int $flags * @param array $attributes * * @return bool */ public function publish($message, $routingKey = null, $flags = Client::NOPARAM, array $attributes = []) { try { return $this->rawExchange->publish($this->encodeStrategy->encode($message), $routingKey, $flags, $attributes); } catch (\Exception $e) { ClientHelper::throwRightException($e); } }
/** * @param string $data * @param array $context */ protected function doPush($data, array $context) { $config = $this->getConfig(); if (false === $this->connected) { if (!extension_loaded('amqp')) { throw new \RuntimeException(sprintf('%s pusher require %s php extension', get_class($this), 'amqp')); } $this->connection = new \AMQPConnection($config); $this->connection->connect(); list(, $this->exchange) = Utils::setupConnection($this->connection, $config); $this->setConnected(); } $resolver = new OptionsResolver(); $resolver->setDefaults(['routing_key' => null, 'publish_flags' => AMQP_NOPARAM, 'attributes' => array()]); $context = $resolver->resolve($context); $this->exchange->publish($data, $context['routing_key'], $context['publish_flags'], $context['attributes']); }
/** * 广播形式写入队列 * * @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')); }
/** * 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; }
/** * 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()); }
/** * (non-PHPdoc) * @see ContentEngine\Request.QueueInterface::push() */ public function push(ItemCollection $collection) { if (!isset($this->exchange)) { throw new \Exception('No AMQP exchange set.'); } $serial = $this->serialiser->serialise($collection); $this->exchange->publish($serial, $this->routingKey); return true; }
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()); } }
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; }
/** * Add message to queue * * @param MessageInterface $message * * @return bool * * @throws \RuntimeException */ public function addMessage(MessageInterface $message) { if (null === $this->routingKey) { throw new \RuntimeException('Can\'t send message. Publish routing key is undefined.'); } if (null === $this->exchange) { throw new \RuntimeException('Can\'t send message. Exchange not found.'); } return $this->exchange->publish(serialize($message), $this->routingKey, $this->publishFlag, $this->publishOptions); }
/** * Publish a message to an exchange. * * Publish a message to the exchange represented by the AMQPExchange object. * * @param string $message The message to publish. * @param string $routing_key The optional routing key to which to * publish to. * @param int $flags One or more of AMQP_MANDATORY and * AMQP_IMMEDIATE. * @param array $attributes One of content_type, content_encoding, * message_id, user_id, app_id, delivery_mode, * priority, timestamp, expiration, type * or reply_to, headers. * * @throws AMQPExchangeException On failure. * @throws AMQPChannelException If the channel is not open. * @throws AMQPConnectionException If the connection to the broker was lost. * * @return bool TRUE on success or FALSE on failure. */ public function publish($message, $routing_key = null, $flags = AMQP_NOPARAM, array $attributes = array()) { if (is_null($routing_key)) { $publishRoutingKey = $this->getPublishRoutingKey(); if ($publishRoutingKey !== '') { $routing_key = $publishRoutingKey; } } return parent::publish($message, $routing_key, $flags, $attributes); }
/** * 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!'); } }
/** * We deliver PERSISTENT messages. * * @param AbstractMessage $message */ public function messagePublish(Message\Message $message, $routingKey) { $metadata = array(); $data = serialize($message); $metadata['timestamp'] = time(); $metadata['delivery_mode'] = self::DELIVERY_MODE_PERSISTENT; $metadata['message_id'] = md5(microtime() . $data); $metadata['content_type'] = 'application/php'; $metadata['content_encoding'] = 'utf8'; parent::publish($data, $routingKey, AMQP_MANDATORY, $metadata); }
/** * @inheritdoc */ public function publish($message, $routingKey = null, $flags = null, array $attributes = []) { try { return $this->delegate->publish($message, $routingKey, self::convertToDelegateFlags($flags), $attributes); } catch (\AMQPExchangeException $e) { throw new ExchangeException($e->getMessage(), $e->getCode(), $e); } catch (\AMQPChannelException $e) { throw new ChannelException($e->getMessage(), $e->getCode(), $e); } catch (\AMQPConnectionException $e) { throw new ConnectionException($e->getMessage(), $e->getCode(), $e); } }
/** * 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); }
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); }
/** * {@inheritdoc} */ public function publish($message, $routingKey = '', array $properties = array()) { $this->replyQueue = $this->declareAnonQueue(); // retrieve the queue name $queueName = $this->replyQueue->getName(); $properties['reply_to'] = $queueName; if (!isset($properties['timestamp'])) { $properties['timestamp'] = microtime(true); } $response = $this->exchange->publish($message, $routingKey, AMQP_NOPARAM, $properties); if ($response == false) { throw new Exception('Message not published!'); } // loop if (isset($this->configuration['timeout'])) { $this->startTime = time(); } $this->waitingForAnswer = true; $message = $this->getMessage($this->replyQueue); if ($message instanceof AMQPEnvelope) { $this->notify($message); } }
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; }
/** * @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()); } }