/** * Execute the console command. * * @return mixed */ public function handle() { //1万次请求测试 $choice = $this->choice('select call thrift rpc times: ', ['1 calls' => 1, '100 calls' => 100, '1000 calls' => 1000, '10000 calls' => 10000], 1); $i = abs($choice); while ($i-- > 0) { try { $host = '127.0.0.1'; $port = 8091; $email = '*****@*****.**'; $info = ['email' => $email, 'name' => '张三', 'userId' => 222]; print "connect {$host}:{$port}...\n\n"; $socket = new TSocket($host, $port); $transport = new TBufferedTransport($socket, 1024, 1024); $protocol = new TBinaryProtocol($transport); $client = new AccountClient($protocol); $transport->open(); $newAccount = new \Demo\AccountInfo($info); $ret = $client->setUserInfo($newAccount); var_dump($ret); $accountInfo = $client->getUserInfoByEmail($email); print_r($accountInfo); $transport->close(); } catch (TException $e) { print 'TException: ' . $e->getMessage() . "\n"; } } }
/** * @param string $host * @param int $port * @param int $sendTimeout msec * @param int $recvTimeout msec * @param bool $framedTransport * @return \Elasticsearch\RestClient */ protected function _createClient($host, $port, $sendTimeout = null, $recvTimeout = null, $framedTransport = false) { $socket = new TSocket($host, $port, true); if (null !== $sendTimeout) { $socket->setSendTimeout($sendTimeout); } if (null !== $recvTimeout) { $socket->setRecvTimeout($recvTimeout); } if ($framedTransport) { $transport = new TFramedTransport($socket); } else { $transport = new TBufferedTransport($socket); } $protocol = new TBinaryProtocolAccelerated($transport); $client = new RestClient($protocol); $transport->open(); return $client; }
public function demoThriftClient() { static $request_count = 0; try { $host = '127.0.0.1'; $port = 8091; $email = '*****@*****.**'; $info = ['email' => $email, 'name' => '张三', 'userId' => 222]; print "connect {$host}:{$port}..." . $request_count++ . "\n\n"; $socket = new TSocket($host, $port); $transport = new TBufferedTransport($socket, 1024, 1024); $protocol = new TBinaryProtocol($transport); $client = new AccountClient($protocol); $transport->open(); $newAccount = new \Demo\AccountInfo(); $ret = $client->setUserInfo($newAccount); // var_dump($ret); $accountInfo = $client->getUserInfoByEmail($email); // var_dump($accountInfo); $transport->close(); return response()->json($accountInfo); } catch (TException $e) { print 'TException: ' . $e->getMessage() . "\n"; } //return view('welcome'); }
public function __construct($keyspace, $server, $credentials = null, $framed_transport = True, $send_timeout = null, $recv_timeout = null) { $this->server = $server; $server = explode(':', $server); $host = $server[0]; if (count($server) == 2) { $port = (int) $server[1]; } else { $port = self::DEFAULT_PORT; } $socket = new TSocket($host, $port); if ($send_timeout) { $socket->setSendTimeout($send_timeout); } if ($recv_timeout) { $socket->setRecvTimeout($recv_timeout); } if ($framed_transport) { $transport = new TFramedTransport($socket, true, true); } else { $transport = new TBufferedTransport($socket, 1024, 1024); } $this->client = new CassandraClient(new TBinaryProtocolAccelerated($transport)); $transport->open(); $this->set_keyspace($keyspace); if ($credentials) { $request = new AuthenticationRequest(array("credentials" => $credentials)); $this->client->login($request); } $this->keyspace = $keyspace; $this->transport = $transport; $this->op_count = 0; }
function getSentimentByFood($cid, $fid) { $host = "localhost"; $port = 9091; $db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME, 3306); try { //Thrift connection handling $socket = new TSocket($host, $port); $transport = new TBufferedTransport($socket, 1024, 1024); $protocol = new TBinaryProtocol($transport); // get our example client $client = new SentiClient($protocol); $transport->open(); $response = ""; $result = ""; // mysql query $check = $db->query("SELECT * FROM reviews where username ='******' and dish = '{$fid}'"); if (mysqli_num_rows($check) > 0) { while ($row = $check->fetch_assoc()) { $response = $response . "|" . $row["review"]; } } else { $response = "error"; } // echo json response //echo $response; $result = $client->getSentiment($response); $transport->close(); } catch (TException $tx) { print 'Something went wrong: ' . $tx->getMessage() . "\n"; } //echo $result; return $result; }
/** * Run server */ public function run() { $transport = new TBufferedTransport(new TPhpStream(TPhpStream::MODE_R | TPhpStream::MODE_W)); $protocol = new $this->config['protocol']($transport, true, true); $transport->open(); $this->processor->process($protocol, $protocol); $transport->close(); }
/** * @param string $host * @param int $port */ function get_thrift($class, $host, $port, $timeout){ $socket = new Thrift\Transport\TSocket($host, $port); $socket->setSendTimeout( $timeout ); $socket->setRecvTimeout( $timeout ); $transport = new TBufferedTransport($socket); $transport->open(); $protocol = new TBinaryProtocol($transport); $client = new $class($protocol); return $client; }
private static function _loadClient() { $socket = new TSocket('182.92.223.200', 9091); $socket->setSendTimeout(20000); $socket->setRecvTimeout(8000000); $transport = new TBufferedTransport($socket); $protocol = new TBinaryProtocol($transport); $transport->open(); self::$client = new \Thrift\MT4WebServiceClient($protocol); $socket->setDebug(TRUE); }
public function __construct($server = '') { $serverClient = $server . '\\' . ucfirst($server) . 'Client'; $portKey = 'rpc.' . $server; $socket = new TSocket('localhost', (int) config($portKey, '')); $transport = new TBufferedTransport($socket, 1024, 1024); $protocol = new TBinaryProtocol($transport); $client = new $serverClient($protocol); $transport->open(); $this->client = $client; }
function getClient($host, $port) { $t1 = microtime(true); $socket = new TSocket($host, $port); $socket->setSendTimeout(10000); $socket->setRecvTimeout(10000); $transport = new TBufferedTransport($socket, 1024, 1024); $transport->open(); $protocol = new TBinaryProtocol($transport); $client = new \KrunchyKreme\KrunchyKremeClient($protocol); $t2 = microtime(true); $timeTaken = round($t2 - $t1, 3); echo 'Time taken to connect: ' . $timeTaken . "\n"; return $client; }
function getTrending($locality) { $host = "localhost"; $port = 9092; $db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME, 3306); try { //Thrift connection handling $socket = new TSocket($host, $port); $transport = new TBufferedTransport($socket); $protocol = new TBinaryProtocol($transport); // get our example client $client = new TopicsClient($protocol); $transport->open(); $response = ""; $result = ""; $local = $locality; // mysql query $check = $db->query("SELECT * FROM comments where locality ='{$local}'"); if (mysqli_num_rows($check) > 0) { while ($row = $check->fetch_assoc()) { $response = $response . "|" . $row["comment"]; } } else { $response = "error"; return ""; } // echo json response //echo $response; $result = $client->getTrending($response); //echo $result; $Topics = array(); foreach (explode("||", $result) as $r) { //echo $r; if ($r != "") { $parts = explode("|", $r); $Topics[$parts[0]] = $parts[1]; } } $transport->close(); } catch (TException $tx) { print 'Something went wrong: ' . $tx->getMessage() . "\n"; } //echo serialize($Topics); return $Topics; }
private function __construct() { $GEN_DIR = realpath(dirname(__FILE__) . '/..') . '/gen-php'; $loader = new ThriftClassLoader(); $loader->registerNamespace('Thrift', __DIR__); $loader->registerDefinition('shared', $GEN_DIR); $loader->registerDefinition('tutorial', $GEN_DIR); $loader->register(); $kafkaUrl = getconfig('kafkaUrl'); $port = getconfig('kafkaPort'); $socket = new TSocket($kafkaUrl, $port); $transport = new TBufferedTransport($socket, 1024, 1024); $transport->open(); $protocol = new TBinaryProtocol($transport); $this->client = new \com\feiniu\kafka\thrift\service\KafkaService($protocol); $this->project = getconfig('kafkaProject'); $this->topic = getconfig('kafkaTopic'); $this->kafkakey = getconfig('kafkaKey'); $this->group = getconfig('kafkaGroup'); //$this->msg = getconfig(''); }
public function process() { /** * Инициализируем трифт транспорт */ $transport = new TBufferedTransport(new TPhpStream(TPhpStream::MODE_R | TPhpStream::MODE_W)); /** * Пока наш клиент не умеет общаться по бинарному протоколу, * инициализируем в зависимости от наличия заголовка */ if (preg_match("/json|plain/i", $_SERVER['CONTENT_TYPE'])) { \Log::info("Init json protocol"); $protocol = new TJSONProtocol($transport); } else { \Log::info("Init binary protocol"); $protocol = new TBinaryProtocol($transport, true, true); } $transport->open(); /** * Создаем хэндлел для обеспечения методов логикой */ $handlerClassName = "{$this->config->service}"; if (!class_exists($handlerClassName)) { throw new \Exception('Handler for service not found "' . $handlerClassName . '"'); } $handler = new $handlerClassName(); /** * Создаем процессор */ $serviceProcessorClassName = "\\{$this->config->namespace}\\{$this->config->service}Processor"; if (!class_exists($serviceProcessorClassName)) { throw new \Exception('Processor not found (' . $serviceProcessorClassName . ')'); } $processor = new $serviceProcessorClassName($handler); /** * Запуск для обработки одного запроса */ $processor->process($protocol, $protocol); $transport->close(); }
ini_set("display_errors", "stderr"); } use Thrift\Protocol\TBinaryProtocol; use Thrift\Transport\TPhpStream; use Thrift\Transport\TBufferedTransport; class HelloHandler implements \Hello\HelloServiceIf { public function ping() { error_log("ping()"); } public function hello($name) { return "Hello {$name}"; } public function helloV2(\Hello\Person $person) { return "Hello {$person->firstName}, {$person->lastName}"; } } header('Content-Type', 'application/x-thrift'); if (php_sapi_name() == 'cli') { echo "\r\n"; } $handler = new HelloHandler(); $processor = new \Hello\HelloServiceProcessor($handler); $transport = new TBufferedTransport(new TPhpStream(TPhpStream::MODE_R | TPhpStream::MODE_W)); $protocol = new TBinaryProtocol($transport, true, true); $transport->open(); $processor->process($protocol, $protocol); $transport->close();
public function actionIndex1() { require_once dirname(\Yii::$app->basePath) . '/Hbase/Hbase.php'; require_once dirname(\Yii::$app->basePath) . '/Hbase/Types.php'; //'/Hbase/THBaseService.php'; /* * * Thrift Test */ $host = '192.168.186.128'; $port = 9090; $socket = new TSocket($host, $port); $socket->setRecvTimeout(10 * 1000); $transport = new TBufferedTransport($socket); $protocol = new TBinaryProtocol($transport); // Create a client $client = new \Hbase\HbaseClient($protocol); $transport->open(); //获得数据表 //$tables = $client->getTableNames(); //创建一个表 //定义列名 $tableName = 'messages'; //$aritcle = new \Hbase\ColumnDescriptor(array('name' => 'aritcle:')); //$author = new \Hbase\ColumnDescriptor(array('name' => 'author:')); //$columns = array($aritcle, $author); //try { // $client->createTable($tableName, $columns); //} catch (\Hbase\AlreadyExists $ex) { // echo '表已经存在,不能重复创建'; //} //删除已经存在的表 //向表内插入数据 //for ($i = 0; $i < 10000; $i++) { // $record = array(new \Hbase\Mutation(array('column' => 'aritcle:title', 'value' => $i))); // $client->mutateRow($tableName, $i, $record,[]); //} //获得数据 $arr = $client->get($tableName, 2, 'aritcle:title', []); // $arr = array foreach ($arr as $k => $v) { // $k = TCell echo "value = {$v->value} , <br> "; echo "timestamp = {$v->timestamp} <br>"; } $transport->close(); exit; //HOW TO GET $tableName = "test_table"; $column_1 = new \TColumn(); $column_1->family = 'cf1'; $column_1->qualifier = 'q1'; $column_2 = new \TColumn(); $column_2->family = 'cf1'; $column_2->qualifier = 'q2'; $columnArray = array($column_1, $column_2); $get = new \TGet(); $get->row = 'a'; $get->columns = $columnArray; if ($client->exists($tableName, $get)) { echo 'Yes'; } else { echo 'No'; } exit; print_r($tables); exit; $arr = $client->get($tableName, $get); $results = $arr->columnValues; foreach ($results as $result) { $qualifier = (string) $result->qualifier; $value = $result->value; print_r($qualifier); print_r($value); } //HOW TO SCAN $scan = new \TScan(); $scan->startRow = 'a'; $scan->stopRow = 'z'; $scan->columns = $columnArray; $num = 1000; $scanRets = $client->getScannerRows($scanId, $num); foreach ($scanRets as $scanRet) { $scan_row = $scanRet->row; $scan_cols = $scanRet->columnValues; print_r($scan_row); print_r($scan_cols); } $client->closeScanner($scanId); $transport->close(); echo 11; exit; }