一、简介
thrift是一个软件框架,用来进行可扩展且跨语言的服务的开发。它结合了功能强大的软件堆栈和代码生成引擎,以构建在 C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, and OCaml 这些编程语言间无缝结合的、高效的服务。在我理解,Thrift就是一种通过接口进行远程通信的框架,这里主要在介绍一下Thrift在PHP中的简单使用。
二、Thrift在PHP中使用
IDL全称为Interface description language,是一种接口描述语言,Thrift是IDL的一种具体实现。可以使用Thrift编译工具,根据脚本文件生成各种不同语言的Service文件。
Thrift传输层采用二进制形式,速度快;数据的输入输出通过协议层来完成。
1.例如 Test.thrift:
service TestService {
# Thrift远程调用测试
string getStr(1:i32 type);
}
客户端和服务端使用脚本文件分别生成相应的代码,命令:
客户端:thrift --gen php Test.thrift
服务端:thrift --gen php:server Test.thrift
生成的TestService代码中,TestServiceClient为客户端的调用逻辑,TestServiceProcessor为服务器端的处理逻辑。
2.接下来,我们需要实现TestService中的TestServiceIf接口,创建服务端代码TestService_Impl.php:
<?php
/*
* TestService接口实现类
*/
class TestService_Impl implements TestServiceIf {
/*
* param 1: int
* return string
*/
public function getStr($type){
switch($type){
case 0:
$return = 'hello world';break;
case 1:
$return = 'You are welcome!';break;
case 2:
$return = 'Read the fuck source code!';break;
}
return $return;
}
}
3.创建服务端实现代码后,将TestService_impl作为实现类传给TestServiceProcessor去处理:
<?php
include 'inc.php';
include 'Services/TestService_Impl.php';
header('Content-type', 'application/x-thrift');
//服务端接口处理类
$class = 'TestServiceProcessor';
$processor = new $class($service);
$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();
4.服务端实现了接口之后,客户端就可以对其进行通信了,主要代码:
<?php
header('Content-type: text/html; charset=utf-8');
include '../inc.php';
//模拟客户端调用服务端Service
$socket = new THttpClient($_SERVER['HTTP_HOST'], 80, '/index.php?srv=TestService_Impl');
$transport = new TBufferedTransport($socket, 1024, 1024);
$protocol = new TBinaryProtocol($transport);
$transport->open();
//创建Service Client对象
$client = new TestServiceClient($protocol);
//调用远程接口
$res = $client->getStr(2);
var_dump($res);
$transport->close ();
5.主要注意事项
客户端调用过程中不能有类似echo之类的输出。
学习
http://thrift.apache.org/,Thrift的源码和编译工具的官网。
http://download.csdn.net/detail/whdsmile/6804629,Thrift的一个PHP示例。