Exemplo n.º 1
0
 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');
 }
Exemplo n.º 2
0
 /**
  * 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";
         }
     }
 }
Exemplo n.º 3
0
 /**
  * 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();
 }
Exemplo n.º 4
0
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;
}
Exemplo n.º 5
0
 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();
 }
Exemplo n.º 6
0
}
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();
Exemplo n.º 7
0
 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;
 }
Exemplo n.º 8
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;
}