Thrift
是支持多种语言的远程服务调用的框架,该框架通过自定义的 Interface Definition Language(IDL)
可以基于RPC
客户端和服务端服务代码
Mac
安装Thrift
brew install thrift
其他平台安装较为麻烦需要安装一系列依赖
安装成功后执行
thrift -version
看到版本号则安装成功.
生成语言为php
的调用方式 创建一个HelloThrift.thrift
文件
namespace php HelloThrift service HelloService { string sayHello(1:string username) }
使用thrift -r --gen php:server HelloThrift.thrift
去在当前目录下生成 一个gen-php
(此处文档写的极不清楚,一开始以为是创建文件夹),并且将 gen-php
改为gen_php
(此处随意)
Notice
但是还是需要下载thrift
的源码
git clone https://git-wip-us.apache.org/repos/asf/thrift.git thrift
将下载的源码lib
目录下的文件cp
到刚才生成文件的根目录下
服务端代码
registerNamespace('Thrift',__DIR__.'/lib/php/lib');$loader->registerDefinition('HelloThrift',$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 HelloHandler implements \HelloThrift\HelloServiceIf { public function sayHello($username) { return "Hello ".$username; }}header('Content-Type','application/x-thrift');if (php_sapi_name() == 'cli') { echo PHP_EOL;}$handler = new HelloHandler();$processor = new \HelloThrift\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();
客户端代码
registerNamespace('Thrift',__DIR__.'/lib/php/lib');$loader->registerDefinition('HelloThrift',$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,'/Server.php'); } else { $socket = new TSocket('localhost',9090); } $transport = new TBufferedTransport($socket,1024,1024); $protocol = new TBinaryProtocol($transport); $client = new \HelloThrift\HelloServiceClient($protocol); $transport->open(); echo $client->sayHello(" World! "); $transport->close();} catch (\Exception $e) { print 'TException:'.$e->getMessage().PHP_EOL;}
一定要确保能够引入配置文件才可以。
在根目录运行php -S localhost:8080
客户端执行php Client --http
可以看到hello
即为成功