protected function receiveMessage() { while (!($queueObject = $this->amq->readFrame())) { } $this->replyQueue = $queueObject->headers['reply-to']; $this->correlationId = $queueObject->headers['correlation-id']; $msg = $queueObject->body; $this->amq->ack($queueObject); return $msg; }
/** * Experimental task to enable kill processing from queue. * @param array $options */ public function stomp_process_queue(array $options) { $this->cli->header("Starting Stomp Import"); $reg = Registry::getInstance(); $log = $reg->getLogger(); $stompcfg = $reg->stomp; if (is_null($stompcfg) || !is_array($stompcfg)) { $this->cli->error("stomp is not configured, see config.php for details"); $log->critical("stomp not configured, exiting"); return; } $stomp = new \Stomp($stompcfg['url'], $stompcfg['user'], $stompcfg['passwd']); // destination has the destination topic (for example /topic/kills) $destination = $reg->stomp['destination_read']; // we subscribe with additional parameters $stomp->subscribe($destination, array("id" => $reg->stomp['dsub_id'], "persistent" => "true", "ack" => "client", "prefetch-count" => 1)); while (true) { try { if (!$stomp->hasFrame()) { continue; } $frame = $stomp->readFrame(); if ($frame) { $log->debug("received frame with message-id: " . $frame->headers['message-id']); $killdata = json_decode($frame->body, true); $existing = Kill::getByKillId($killdata["killID"]); if (!is_null($existing)) { $log->debug($frame->headers['message-id'] . '::' . $killdata["killID"] . " kill by killID exists"); $stomp->ack($frame); continue; } try { $apiParser = new EveAPI(); $apiParser->parseKill($killdata); $log->debug($frame->headers['message-id'] . '::' . $killdata["killID"] . " saved"); $stomp->ack($frame); } catch (\Exception $e) { $log->error($frame->headers['message-id'] . "could not be saved, exception: " . $e->getMessage()); } } } catch (\StompException $e) { $log->error("there was some kind of error with stomp: " . $e->getMessage()); $log->info("going to sleep for 10, retrying then"); // we have a stomp exception here most likely that means that the server died. // so we are going to sleep for a bit and retry sleep(10); // replace stomp connection by new one // @todo: check if that might cause open connections not to close over time unset($stomp); $stomp = new \Stomp($stompcfg['url'], $stompcfg['user'], $stompcfg['passwd']); $stomp->subscribe($destination, array("id" => $reg->stomp['dsub_id'], "persistent" => "true", "ack" => "client", "prefetch-count" => 1)); $log->info("stomp process retrying"); } } }
public function loop() { $d = EventDispatcher::get(); if (!$this->stomp) { $this->connect(); } while (true) { if ($this->stomp->hasFrame()) { $msg = $this->stomp->readFrame(); $destination = $msg->headers['destination']; /** @var Topics\AbstractTopic $topic */ $topic = $this->eventTopics[$destination]; //$factory = "\\OpenRailData\\NetworkRail\\Services\\Stomp\\Events\\" . $topic->getFactory() . "\\Factory"; // Save events locally so we can ack the message. $events = []; foreach (json_decode($msg->body) as $raw) { $events[] = $raw; } $this->stomp->ack($msg); foreach ($events as $event) { $d->dispatch("raw" . $topic->getEventName(), new StompEvent($event)); } } } }
/** * @param InputInterface $input * @param OutputInterface $output * * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { //Init rena $app = RenaApp::getInstance(); $startTime = time() + 3600; // Current time + 60 minutes $run = true; $stomp = new \Stomp($app->baseConfig->getConfig("server", "stomp"), $app->baseConfig->getConfig("username", "stomp"), $app->baseConfig->getConfig("password", "stomp")); $stomp->subscribe("/topic/kills", array("id" => "projectRena", "persistent" => "true", "ack" => "client", "prefetch-count" => 1)); do { $frame = $stomp->readFrame(); if (!empty($frame)) { $killdata = json_decode($frame->body, true); if (!empty($killdata)) { $app->StatsD->increment("stompReceived"); if (isset($killdata["_stringValue"])) { unset($killdata["_stringValue"]); } // Fix the killID $killdata["killID"] = (int) $killdata["killID"]; $json = json_encode($killdata, JSON_NUMERIC_CHECK); $hash = hash("sha256", ":" . $killdata["killTime"] . ":" . $killdata["solarSystemID"] . ":" . $killdata["moonID"] . "::" . $killdata["victim"]["characterID"] . ":" . $killdata["victim"]["shipTypeID"] . ":" . $killdata["victim"]["damageTaken"] . ":"); $inserted = $app->Db->execute("INSERT IGNORE INTO killmails (killID, hash, source, kill_json) VALUES (:killID, :hash, :source, :kill_json)", array(":killID" => $killdata["killID"], ":hash" => $hash, ":source" => "stomp", ":kill_json" => $json)); if ($inserted > 0) { // Push it over zmq to the websocket $context = new ZMQContext(); $socket = $context->getSocket(ZMQ::SOCKET_PUSH, "rena"); $socket->connect("tcp://localhost:5555"); $socket->send($json); } } $stomp->ack($frame->headers["message-id"]); } // Kill it after an hour if ($startTime <= time()) { $run = false; } } while ($run == true); }
public function events() { if (!$this->stomp) { $this->connect(); } while (true) { if ($this->stomp->hasFrame()) { $msg = $this->stomp->readFrame(); $destination = $msg->headers['destination']; $factory = "\\OpenRailData\\Events\\" . $this->eventFactories[$destination] . "\\Factory"; // Save events locally so we can ack the message. $events = []; foreach (json_decode($msg->body) as $rawEevent) { $events[] = $factory::create($rawEevent); } $this->stomp->ack($msg); foreach ($events as $event) { (yield $event); } } } }
/** * @param InputInterface $input * @param OutputInterface $output * * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { //Init rena /** @var RenaApp $app */ $app = RenaApp::getInstance(); $startTime = time() + 3600; // Current time + 60 minutes $run = true; $stomp = new \Stomp($app->baseConfig->getConfig("server", "stomp"), $app->baseConfig->getConfig("username", "stomp"), $app->baseConfig->getConfig("password", "stomp")); $stomp->subscribe("/topic/kills", array("id" => $app->baseConfig->getConfig("queueName", "stomp", "projectRena"), "persistent" => "true", "ack" => "client", "prefetch-count" => 1)); do { $frame = $stomp->readFrame(); if (!empty($frame)) { $killdata = json_decode($frame->body, true); if (!empty($killdata)) { $app->StatsD->increment("stompReceived"); if (isset($killdata["_stringValue"])) { unset($killdata["_stringValue"]); } // Fix the killID $killdata["killID"] = (int) $killdata["killID"]; $json = json_encode($killdata, JSON_NUMERIC_CHECK); $hash = $app->CrestFunctions->generateCRESTHash($killdata); $inserted = $app->killmails->insertIntoKillmails($killdata["killID"], 0, $hash, "stomp", $json); if ($inserted > 0) { \Resque::enqueue("turbo", "\\ProjectRena\\Task\\Resque\\upgradeKillmail", array("killID" => $killdata["killID"])); } } $stomp->ack($frame->headers["message-id"]); } // Kill it after an hour if ($startTime <= time()) { $run = false; } } while ($run == true); }
<?php require_once 'Stomp.php'; $stomp = new Stomp("tcp://localhost:61613"); $stomp->connect('system', 'manager'); $stomp->subscribe("/topic/STOCKS.JAVA"); $stomp->subscribe("/topic/STOCKS.IONA"); $i = 0; while ($i++ < 100) { $frame = $stomp->readFrame(); $xml = new SimpleXMLElement($frame->body); echo $xml->attributes()->name . "\t" . number_format($xml->price, 2) . "\t" . number_format($xml->offer, 2) . "\t" . ($xml->up == "true" ? "up" : "down") . "\n"; $stomp->ack($frame); } $stomp->disconnect();
$stomp = new Stomp($stompServer, $stompUser, $stompPassword); } catch (Exception $ex) { Util::out("Stomp error: " . $ex->getMessage()); exit; } $stomp->setReadTimeout(1); foreach ($topics as $topic) { $stomp->subscribe($topic, array('id' => 'zkb-' . $baseAddr, 'persistent' => 'true', 'ack' => 'client', 'prefetch-count' => 1)); } $stompCount = 0; $timer = new Timer(); while ($timer->stop() <= 59000) { $frame = $stomp->readFrame(); if (!empty($frame)) { $killdata = json_decode($frame->body, true); $killID = (int) $killdata['killID']; if ($killID == 0) { continue; } $hash = $hash = Killmail::getCrestHash($killID, $killdata); $killdata['killID'] = (int) $killID; if (!$mdb->exists('crestmails', ['killID' => $killID, 'hash' => $hash])) { ++$stompCount; $i = $mdb->getCollection('crestmails')->insert(['killID' => $killID, 'hash' => $hash, 'processed' => false, 'source' => 'stomp', 'added' => $mdb->now()]); } $stomp->ack($frame->headers['message-id']); } } if ($stompCount > 0) { Util::out("New kills from STOMP: {$stompCount}"); }
*/ /* To successfully run this example, you must first start the broker with stomp+ssl enabled. You can do that by executing: $ ${ACTIVEMQ_HOME}/bin/activemq xbean:activemq-connectivity.xml Then you can execute this example with: $ php connectivity.php */ // include a library require_once "Stomp.php"; // make a connection $con = new Stomp("failover://(tcp://localhost:61614,ssl://localhost:61612)?randomize=false"); // connect $con->connect(); // send a message to the queue $con->send("/queue/test", "test"); echo "Sent message with body 'test'\n"; // subscribe to the queue $con->subscribe("/queue/test"); // receive a message from the queue $msg = $con->readFrame(); // do what you want with the message if ($msg != null) { echo "Received message with body '{$msg->body}'\n"; // mark the message as received in the queue $con->ack($msg); } else { echo "Failed to receive a message\n"; } // disconnect $con->disconnect();
} else { echo "Failed to receive a message\n"; } sleep(1); // disconnect durable consumer $consumer->unsubscribe("/topic/test"); $consumer->disconnect(); echo "Disconnecting consumer\n"; // send a message while consumer is disconnected // note: only persistent messages will be redelivered to the durable consumer $producer->send("/topic/test", "test1", array('persistent' => 'true')); echo "Message 'test1' sent to topic\n"; // reconnect the durable consumer $consumer = new Stomp("tcp://localhost:61613"); $consumer->clientId = "test"; $consumer->connect(); $consumer->subscribe("/topic/test"); echo "Reconnecting consumer\n"; // receive a message from the topic $msg = $consumer->readFrame(); // do what you want with the message if ($msg != null) { echo "Message '{$msg->body}' received from topic\n"; $consumer->ack($msg); } else { echo "Failed to receive a message\n"; } // disconnect $consumer->unsubscribe("/topic/test"); $consumer->disconnect(); $producer->disconnect();
public function dealSkuStock() { require __DOCROOT__ . '/Stomp.php'; require __DOCROOT__ . '/Stomp/Message/Map.php'; $consumer = new Stomp($this->conf['service']['activeMq']); $consumer->clientId = "inventorySkuStock"; $consumer->connect(); $consumer->subscribe($this->conf['topic']['skuStock'], array('transformation' => 'jms-map-json')); $msg = $consumer->readFrame(); if ($msg != null) { $consumer->ack($msg); if ($msg->map['stock'] <= 0 && $msg->map['operate'] == "+") { $sql = "select status from sku_status_history where sku = '" . $msg->map['sku'] . "' order by id desc limit 0,1"; $result = mysql_query($sql, $this->conn); $row = mysql_fetch_assoc($result); $this->log("dealSkuStock", print_r($msg->map, true) . "<br>"); $this->updateCustomFieldValueBySku($msg->map['sku'], $this->conf['fieldArray']['skuStatus'], $this->conf['skuStatus'][str_replace(" ", "_", $row['status'])]); } } else { echo date("Y-m-d H:i:s") . " no message\n"; } $consumer->disconnect(); }
$con->begin("tx2"); echo "Sent messages {\n"; for ($i = 1; $i < 5; $i++) { echo "\t{$i}\n"; $con->send("/queue/transactions", $i, array("transaction" => "tx2")); } echo "}\n"; // they will be available for consumers after commit $con->commit("tx2"); // try to receive some messages $con->begin("tx3"); $messages = array(); for ($i = 1; $i < 3; $i++) { $msg = $con->readFrame(); array_push($messages, $msg); $con->ack($msg, "tx3"); } // of we abort transaction, we will "rollback" out acks $con->abort("tx3"); $con->begin("tx4"); // so we need to ack received messages again // before we can receive more (prefetch = 1) if (count($messages) != 0) { foreach ($messages as $msg) { $con->ack($msg, "tx4"); } } // now receive more messages for ($i = 1; $i < 3; $i++) { $msg = $con->readFrame(); $con->ack($msg, "tx4");
public function dealSkuOutOfStockMessage() { require_once __DOCROOT__ . '/Stomp.php'; require_once __DOCROOT__ . '/Stomp/Message/Map.php'; $consumer = new Stomp($this->config['service']['activeMQ']); $consumer->clientId = "eBayListingSkuOutOfStock"; $consumer->connect(); $consumer->subscribe($this->config['topic']['skuOutOfStock'], array('transformation' => 'jms-map-json')); //for($i=0; $i<6; $i++){ $msg = $consumer->readFrame(); if ($msg != null) { //echo "Message '$msg->body' received from queue\n"; //print_r($msg->map); $consumer->ack($msg); $sku_array = explode(",", $msg->map['sku']); foreach ($sku_array as $sku) { $sql = "update template set status = 3 where SKU = '" . $sku . "' and status = 6"; echo $sql . "\n"; $result = mysql_query($sql, Cron::$database_connect); } } else { echo date("Y-m-d H:i:s") . " no message\n"; } //sleep(1); //} $consumer->disconnect(); }
public function dealSkuStockMessage() { require_once 'Stomp.php'; require_once 'Stomp/Message/Map.php'; $consumer = new Stomp($this->conf['service']['activeMq']); $consumer->clientId = "inventory"; $consumer->connect(); $consumer->subscribe("/topic/SkuOutStock", array('transformation' => 'jms-map-json')); while (1) { $msg = $consumer->readFrame(); if ($msg != null) { //echo "Message '$msg->body' received from queue\n"; //print_r($msg->map); //$this->inventoryTakeOut($msg->map['inventory_model'], $msg->map['quantity'], $msg->map['shipment_id'], $msg->map['shipment_method']); $consumer->ack($msg); } sleep(1); } }
public function execute($parameters, $db) { global $stompServer, $stompUser, $stompPassword, $baseAddr; // Ensure the class exists if (!class_exists("Stomp")) { die("ERROR! Stomp not installed! Check the README to learn how to install Stomp...\n"); } // Build the topic from Admin's tracker list $adminID = $db->queryField("select id from zz_users where username = '******'", "id", array(), 0); $trackers = $db->query("select locker, content from zz_users_config where locker like 'tracker_%' and id = :id", array(":id" => $adminID), array(), 0); $topics = array(); foreach ($trackers as $row) { $entityType = str_replace("tracker_", "", $row["locker"]); $entities = json_decode($row["content"], true); foreach ($entities as $entity) { $id = $entity["id"]; $topic = "/topic/involved.{$entityType}.{$id}"; $topics[] = $topic; } } if (sizeof($topics) == 0) { $topics[] = "/topic/kills"; } try { $stomp = new Stomp($stompServer, $stompUser, $stompPassword); $stomp->setReadTimeout(1); foreach ($topics as $topic) { $stomp->subscribe($topic, array("id" => "zkb-" . $baseAddr, "persistent" => "true", "ack" => "client", "prefetch-count" => 1)); } $stompCount = 0; $timer = new Timer(); while ($timer->stop() < 60000) { $frame = $stomp->readFrame(); if (!empty($frame)) { $killdata = json_decode($frame->body, true); if (!empty($killdata)) { $killID = $killdata["killID"]; $count = $db->queryField("SELECT count(1) AS count FROM zz_killmails WHERE killID = :killID LIMIT 1", "count", array(":killID" => $killID), 0); if ($count == 0) { if ($killID > 0) { $hash = Util::getKillHash(null, json_decode($frame->body)); $db->execute("INSERT IGNORE INTO zz_killmails (killID, hash, source, kill_json) values (:killID, :hash, :source, :json)", array("killID" => $killID, ":hash" => $hash, ":source" => "stompQueue", ":json" => json_encode($killdata))); $stomp->ack($frame->headers["message-id"]); $stompCount++; continue; } else { $stomp->ack($frame->headers["message-id"]); continue; } } else { $stomp->ack($frame->headers["message-id"]); continue; } } } } if ($stompCount > 0) { Log::log("StompReceive Ended - Received {$stompCount} kills"); } } catch (Exception $ex) { $e = print_r($ex, true); Log::log("StompReceive ended with the error:\n{$e}\n"); } }
<?php $broker = 'tcp://localhost:61613'; $queue = '/queue/foo'; $msg = 'bar'; try { $stomp = new Stomp($broker); $stomp->send($queue, $msg); $stomp->subscribe($queue); $frame = $stomp->readFrame(); if ($frame->body === $msg) { echo "Worked\n"; $stomp->ack($frame, array('receipt' => 'message-12345')); } else { echo "Failed\n"; } $stomp->disconnect(); } catch (StompException $e) { echo $e->getMessage(); }