您的位置:首页 > 编程语言 > PHP开发

Mac安装Thrift

2017-08-04 13:53 267 查看
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
到刚才生成文件的根目录下

服务端代码

<?php
namespace HelloThrift\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('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();

客户端代码

<?php
namespace  HelloThrift\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('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
即为成功
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Thrift PHP