/** * 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"); } } }
/** * Subscribe to an ActiveMQ topic. * * This can be done before the connection starts (topic will be queued for * addition) or when the connection is open (topic will be subscribed to * the open connection immediately). * * @param \OpenRailData\NetworkRail\Services\Stomp\Topic\AbstractTopic */ public function addTopic(AbstractTopic $topic) { /** * If the stomp connection is not yet open, then queue the topic * for adding later. */ if (!$this->stomp) { $this->enqueueTopic($topic); return; } $stompTopic = "/topic/" . $topic->getTopic(); $this->eventTopics[$stompTopic] = $topic; $this->stomp->subscribe($stompTopic); // Once the topic has been subscribed to, we can handle the event // listener $topic->listen(); }
/** * @param string $queueName * * @return bool * @throws Exception * @throws StompException */ public function subscribe($queueName = null) { if (empty($queueName)) { $queueName = INIT::$QUEUE_NAME; } if (!empty($this->clientType) && $this->clientType != self::CLIENT_TYPE_SUBSCRIBER) { throw new Exception("This client is a {$this->clientType}. A client can only publisher or subscriber, not both."); } elseif ($this->clientType == self::CLIENT_TYPE_SUBSCRIBER) { //already connected, we want to change the queue $this->queueName = $queueName; return parent::subscribe('/queue/' . INIT::$QUEUE_NAME); } $this->clientType = self::CLIENT_TYPE_SUBSCRIBER; $this->connect(); $this->setReadTimeout(5, 0); $this->queueName = $queueName; return parent::subscribe('/queue/' . $queueName); }
/** * @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); }
/** * Subscribe to an ActiveMQ topic. * * This can be done before the connection starts (topic will be queued for * addition) or when the connection is open (topic will be subscribed to * the open connection immediately). * * @param \OpenRailData\Topics\AbstractTopic $topic */ public function addTopic(AbstractTopic $topic) { /** * If the stomp connection is not yet open, then queue the topic * for adding later. */ if (!$this->stomp) { $this->enqueueTopic($topic); return; } /** * Sanity checks. Make sure the topic is a Network Rail / Stomp topic. */ if ($topic->getCommunicationType() !== AbstractTopic::COMMS_TYPE_REALTIME) { throw new IncompatibleTopicException(sprintf("Topic %s is not a realtime topic and is not supported by this connection type.", $topic->getTopic())); } if ($topic->getServiceProvider() !== AbstractTopic::PROVIDER_NETWORK_RAIL) { throw new IncompatibleTopicException(sprintf("Topic %s is not a network rail topic.", $topic->getTopic())); } $stompTopic = "/topic/" . $topic->getTopic(); $this->eventFactories[$stompTopic] = $topic->getFactory(); $this->stomp->subscribe($stompTopic); }
/** * @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); }
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(); }
* * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // include a library require_once "Stomp.php"; // make a connection $con = new Stomp("tcp://localhost:61613"); // connect $con->connect(); $con->setReadTimeout(1); // subscribe to the queue $con->subscribe("/queue/transactions", array('ack' => 'client', 'activemq.prefetchSize' => 1)); // try to send some messages $con->begin("tx1"); for ($i = 1; $i < 3; $i++) { $con->send("/queue/transactions", $i, array("transaction" => "tx1")); } // if we abort transaction, messages will not be sent $con->abort("tx1"); // now send some messages for real $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";
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(); }
protected function initServer() { $this->amq = new \Stomp($this->socket); $this->amq->subscribe($this->queue); }
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 require_once('Stomp/Stomp.php'); $conn = new Stomp("tcp://localhost:61613"); $file = 'fedora_rss.xml'; echo "connecting...."; $conn->connect(); echo " done!\n"; echo "\nWaiting...\n"; $conn->subscribe("/topic/fedora.apim.update"); while (1) { if (($msg = $conn->readFrame()) !== false) { $mess = (string) $msg; $mess = implode("\n", array_slice(explode("\n", $mess), 9)); $date = date('r'); $xml = new DOMDocument(); $xml->loadXML($mess); $tag = $xml->getElementsByTagName('title')->item(0)->nodeValue; echo 'Event type: ' . $tag . "\n"; $pid = $xml->getElementsByTagName('content')->item(0)->nodeValue; echo 'pid: ' . $pid . "\n"; $check = check_url('http://192.168.56.103:8080/fedora/objects/' . $pid . '/datastreams/FULL_SIZE/content'); var_dump($check); if ($tag == 'ingest' && $check) { if (!file_exists($file)) { $rss = '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\n"; $rss .= '<rss version="2.0">' . "\n"; $rss .= '<channel>' . "\n"; $rss .= '<title>New fedora images</title>' . "\n"; $rss .= '<item>' . "\n";
Then you can execute this example with: $ php connectivity.php */ // include a library #require_once("Stomp.php"); // make a connection try { $con = new Stomp("tcp://localhost:61613"); // connect #$con->connect(); #// send a message to the queue #$con->send("/topic/fedora.apim.update", "test"); #echo "Sent message with body 'test'\n"; // subscribe to the queue $con->subscribe("/queue/fedora.apim.update"); // receive a message from the queue while (true) { $msg = $con->readFrame(); // do what you want with the message if ( $msg != null) { $con->ack($msg); echo "Received message with body '$msg->body'\n"; // mark the message as received in the queue var_dump($msg->headers['pid']); } else { echo "Failed to receive a message\n"; } }
* See the License for the specific language governing permissions and * limitations under the License. */ // include a library require_once "Stomp.php"; require_once "Stomp/Message/Map.php"; // make a connection $con = new Stomp("tcp://localhost:61613"); // connect $con->connect(); // send a message to the queue $body = array("city" => "Belgrade", "name" => "Dejan"); $header = array(); $header['transformation'] = 'jms-map-json'; $mapMessage = new StompMessageMap($body, $header); $con->send("/queue/test", $mapMessage); echo "Sending array: "; print_r($body); $con->subscribe("/queue/test", array('transformation' => 'jms-map-json')); $msg = $con->readFrame(); // extract if ($msg != null) { echo "Received array: "; print_r($msg->map); // 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();
*/ /* 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();
$host = "localhost"; } $port = getenv("APOLLO_PORT"); if (!$port) { $port = 61613; } $destination = '/topic/event'; function now() { list($usec, $sec) = explode(' ', microtime()); return (double) $usec + (double) $sec; } try { $url = 'tcp://' . $host . ":" . $port; $stomp = new Stomp($url, $user, $password); $stomp->subscribe($destination); $start = now(); $count = 0; echo "Waiting for messages...\n"; while (true) { $frame = $stomp->readFrame(); if ($frame) { if ($frame->command == "MESSAGE") { if ($frame->body == "SHUTDOWN") { $diff = round(now() - $start, 2); echo "Received " . $count . " in " . $diff . " seconds\n"; break; } else { if ($count == 0) { $start = now(); }
require_once '../init.php'; global $stompListen; if ($stompListen != true) { exit; } $topics[] = '/topic/kills'; try { $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;
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); } }
<?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();
<?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(); }