php使用thrift做服務端開發
thrift採用接口描述語言定義和創建服務,用二進位格式傳輸數據,體積更小、效率更高,對於高並發、數據量大和多語言的環境有更好的支持。
Apache Thrift是啥?
Apache Thrift是FaceBook開發的一套可擴展的、跨語言的服務調用框架。簡單的說就是先定義一個配置文件,不同的語言可以利用thrift基於這個配置文件生成各自語言的服務端,不管客戶端用什麼語言,都可以調用,也就是說基於thrift協議用java可以調用php的服務。目前支持C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, OCaml and Delphi等語言之間相互調用。
相對於傳統的xml和json等數據傳輸方式來說,thrift採用接口描述語言定義和創建服務,用二進位格式傳輸數據,體積更小、效率更高,對於高並發、數據量大和多語言的環境有更好的支持。
thrift安裝環境要求
如果沒安裝lex和yacc的話要先安裝,否則會make失敗,提示lex和yacc command not found錯誤(一般的機器貌似都沒安,Ubuntu用apt-get install flex bision即可)。
安裝thrift
1.下載最新版thrift:
wget http://www.apache.org/dyn/closer.cgi?path=/thrift/0.9.3/thrift-0.9.3.tar.gztar xvf thrift-0.9.3.tar.gzcd thrift-0.9.32.創建configure文件
./bootstrap.sh./configuremakemake checkmake install編譯選項
thrift for php安裝環境要求
php使用thrift的時候,除了要將thrift/lib/php/lib裡的基礎文件copy到項目目錄下,還需要將根據配置文件生成的php文件也copy到packages文件夾下,並引入到項目中,這個後續會詳細講。
類庫說明
數據傳輸格式(protocol)
定義的了傳輸內容,對Thrift Type的打包解包,包括:
數據傳輸方式(transport)
定義了如何發送(write)和接收(read)數據,包括:
TBufferedTransport,緩存傳輸,寫入數據並不立即開始傳輸,直到刷新緩存。
TSocket,使用socket傳輸
TFramedTransport,採用分塊方式進行傳輸,具體傳輸實現依賴其他傳輸方式,比如TSocket
TCurlClient,使用curl與服務端交互
THttpClient,採用stream方式與HTTP服務端交互
TMemoryBuffer,使用內存方式交換數據
TPhpStream,使用PHP標準輸入輸出流進行傳輸
TNullTransport,關閉數據傳輸
TSocketPool在TSocket基礎支持多個服務端管理(需要APC支持),自動剔除無效的伺服器
開發流程
1、定義IDL(Interface description language)接口描述文件,後綴.thrift
IDL規範:http://thrift.apache.org/docs/idl
thrift types:http://thrift.apache.org/docs/types
2、服務端代碼開發
3、客戶端編寫接入代碼
IDL:
1.tutorial.thriftinclude "shared.thrift"namespace php tutorialtypedef i32 MyIntegerconst i32 INT32CONSTANT = 9853const map<string,string> MAPCONSTANT = {'hello':'world', 'goodnight':'moon'}enum Operation { ADD = 1, SUBTRACT = 2, MULTIPLY = 3, DIVIDE = 4}struct Work { 1: i32 num1 = 0, 2: i32 num2, 3: Operation op, 4: optional string comment,}exception InvalidOperation { 1: i32 whatOp, 2: string why}service Calculator extends shared.SharedService { void ping(), i32 add(1:i32 num1, 2:i32 num2), i32 calculate(1:i32 logid, 2:Work w) throws (1:InvalidOperation ouch), oneway void zip()}2.shared.thrift
namespace php sharedstruct SharedStruct { 1: i32 key 2: string value}service SharedService { SharedStruct getStruct(1: i32 key)}php服務端
<?phpnamespace tutorial\php;ini_set('display_errors',1);error_reporting(E_ALL);require_once __DIR__.'/../../lib/php/lib/Thrift/ClassLoader/ThriftClassLoader.php';use Thrift\ClassLoader\ThriftClassLoader;$GEN_DIR = realpath(dirname(__FILE__).'/..').'/gen-php';$loader = new ThriftClassLoader();$loader->registerNamespace('Thrift', __DIR__ . '/../../lib/php/lib');$loader->registerDefinition('shared', $GEN_DIR);$loader->registerDefinition('tutorial', $GEN_DIR);$loader->register();if (php_sapi_name() == 'cli') { ini_set("display_errors", "stderr");}use Thrift\Protocol\TBinaryProtocol; use Thrift\Transport\TPhpStream; use Thrift\Transport\TBufferedTransport; class CalculatorHandler implements \tutorial\CalculatorIf { protected $log = array(); public function ping() { error_log("ping()"); } public function add($num1, $num2) { error_log("add({$num1}, {$num2})"); return $num1 + $num2; } public function calculate($logid, \tutorial\Work $w) { error_log("calculate({$logid}, {{$w->op}, {$w->num1}, {$w->num2}})"); switch ($w->op) { case \tutorial\Operation::ADD: $val = $w->num1 + $w->num2; break; case \tutorial\Operation::SUBTRACT: $val = $w->num1 - $w->num2; break; case \tutorial\Operation::MULTIPLY: $val = $w->num1 * $w->num2; break; case \tutorial\Operation::DIVIDE: if ($w->num2 == 0) { $io = new \tutorial\InvalidOperation(); $io->whatOp = $w->op; $io->why = "Cannot divide by 0"; throw $io; } $val = $w->num1 / $w->num2; break; default: $io = new \tutorial\InvalidOperation(); $io->whatOp = $w->op; $io->why = "Invalid Operation"; throw $io; } $log = new \shared\SharedStruct(); $log->key = $logid; $log->value = (string)$val; $this->log[$logid] = $log; return $val; } public function getStruct($key) { error_log("getStruct({$key})"); return new \shared\SharedStruct(array("key" => $key, "value" => "PHP is stateless!")); } public function zip() { error_log("zip()"); }};header('Content-Type', 'application/x-thrift');if (php_sapi_name() == 'cli') { echo "\r\n";}$handler = new CalculatorHandler();$processor = new \tutorial\CalculatorProcessor($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();php客戶端
<?phpnamespace tutorial\php;error_reporting(E_ALL);require_once __DIR__.'/../../lib/php/lib/Thrift/ClassLoader/ThriftClassLoader.php';use Thrift\ClassLoader\ThriftClassLoader;$GEN_DIR = realpath(dirname(__FILE__).'/..').'/gen-php';$loader = new ThriftClassLoader();$loader->registerNamespace('Thrift', __DIR__ . '/../../lib/php/lib');$loader->registerDefinition('shared', $GEN_DIR);$loader->registerDefinition('tutorial', $GEN_DIR);$loader->register();use Thrift\Protocol\TBinaryProtocol;use Thrift\Transport\TSocket;use Thrift\Transport\THttpClient;use Thrift\Transport\TBufferedTransport;use Thrift\Exception\TException;try { if (array_search('--http', $argv)) { $socket = new THttpClient('localhost', 8080, '/php/PhpServer.php'); } else { $socket = new TSocket('localhost', 9090); } $transport = new TBufferedTransport($socket, 1024, 1024); $protocol = new TBinaryProtocol($transport); $client = new \tutorial\CalculatorClient($protocol); $transport->open(); $client->ping(); print "ping()\n"; $sum = $client->add(1,1); print "1+1=$sum\n"; $work = new \tutorial\Work(); $work->op = \tutorial\Operation::DIVIDE; $work->num1 = 1; $work->num2 = 0; try { $client->calculate(1, $work); print "Whoa! We can divide by zero?\n"; } catch (\tutorial\InvalidOperation $io) { print "InvalidOperation: $io->why\n"; } $work->op = \tutorial\Operation::SUBTRACT; $work->num1 = 15; $work->num2 = 10; $diff = $client->calculate(1, $work); print "15-10=$diff\n"; $log = $client->getStruct(1); print "Log: $log->value\n"; $transport->close();} catch (TException $tx) { print 'TException: '.$tx->getMessage()."\n";}輸出:
ping()1+1=2InvalidOperation: Cannot divide by 015-10=5Log: PHP is stateless!