转 thrift 轻松实现多语言跨服务器通信

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

作者:ys250

来源:http://www.ys250.com/2010/07/03/thrift_py_php/

 

thrift是由facebook开发的轻量级跨语言的服务框架,现在已经移交到apache基金会下。和他类似的是google出的protocol buffer和ice。 thrift的一大优势就是支持的语言很丰富,它使用自己的IDL语言来描述服务接口和数据交换的格式。

 

官方网站:http://incubator.apache.org/thrift/

 

一、安装:

yum -y install gcc-c++ autoconf automake sysconftool boost /    boost-devel libtool perl-ExtUtils-MakeMaker gettext-base /    gettext gettext-devel liblocale-gettext-perl zlib-devel /    byacc bison flex pkgconfig python-devel  wget http://apache.freelamp.com/incubator/thrift/0.2.0-incubating/thrift-0.2.0-incubating.tar.gz ./bootstrap.sh ./configure --prefix=/usr/local/thrift --with-ruby=no --with-erlang=no --with-java=no --with-csharp=no --enable-gen-java=no --enable-gen-csharp=no --enable-gen-rb=no --enable-gen-erl=nomakemake install

二、IDL描述:

  1.  <textarea name="code" class="c-sharp" rows="15" cols="50"># 1.支持的变量类型  
  2.    
  3. 类型          描述    
  4. bool            #truefalse    
  5. byte            #8位的有符号整数    
  6. i16             #16位的有符号整数    
  7. i32             #32位的有符号整数    
  8. i64             #64位的有符号整数    
  9. double          #64位的浮点数    
  10. string          #UTF-8编码的字符串    
  11. binary          #字符数组    
  12. struct          #结构体    
  13. list<type>        #有序的元素列表,类似于STL的vector    
  14. set<type>     #无序的不重复元素集,类似于STL的set    
  15. map<type1,type2>  #key-value型的映射,类似于STL的map    
  16. exception       #是一个继承于本地语言的exception基类    
  17. service         #服务包含多个函数接口(纯虚函数)    
  18.    
  19. # 2.摘一段例子上来,让瞧瞧这是啥东东。(本例子文件名为:tutorial.thrift,是本身带的教程。)  
  20. include "shared.thrift"  
  21.    
  22.    
  23. namespace cpp tutorial  
  24. namespace java tutorial  
  25. namespace php tutorial  
  26. namespace perl tutorial  
  27. namespace smalltalk.category Thrift.Tutorial  
  28.    
  29. typedef i32 MyInteger  
  30.    
  31. const i32 INT32CONSTANT = 9853  
  32. const map<string,string> MAPCONSTANT = {'hello':'world''goodnight':'moon'}  
  33.    
  34. enum Operation {  
  35.   ADD = 1,  
  36.   SUBTRACT = 2,  
  37.   MULTIPLY = 3,  
  38.   DIVIDE = 4  
  39. }  
  40.    
  41. struct Work {  
  42.   1: i32 num1 = 0,  
  43.   2: i32 num2,  
  44.   3: Operation op,  
  45.   4: optional string comment,  
  46. }  
  47.    
  48. exception InvalidOperation {  
  49.   1: i32 what,  
  50.   2: string why  
  51. }  
  52.    
  53. service Calculator extends shared.SharedService {  
  54.    
  55.    void ping(),  
  56.    
  57.    i32 add(1:i32 num1, 2:i32 num2),  
  58.    
  59.    i32 calculate(1:i32 logid, 2:Work w) throws (1:InvalidOperation ouch),  
  60.    
  61.    oneway void zip()  
  62.    
  63. }  
  64.    
  65. # 3. 我们来写个 helloworld.thrift  
  66.    
  67. service HelloWorld{  
  68.  string ping(1: string name),  
  69.  string getpng(),  
  70. }</textarea>  
 
    
    
[c-sharp] view plain copy print ?
  1. # 1.支持的变量类型  
  2.    
  3. 类型          描述    
  4. bool            #truefalse    
  5. byte            #8位的有符号整数    
  6. i16             #16位的有符号整数    
  7. i32             #32位的有符号整数    
  8. i64             #64位的有符号整数    
  9. double          #64位的浮点数    
  10. string          #UTF-8编码的字符串    
  11. binary          #字符数组    
  12. struct          #结构体    
  13. list<type>        #有序的元素列表,类似于STL的vector    
  14. set<type>     #无序的不重复元素集,类似于STL的set    
  15. map<type1,type2>  #key-value型的映射,类似于STL的map    
  16. exception       #是一个继承于本地语言的exception基类    
  17. service         #服务包含多个函数接口(纯虚函数)    
  18.   
  19. # 2.摘一段例子上来,让瞧瞧这是啥东东。(本例子文件名为:tutorial.thrift,是本身带的教程。)  
  20. include "shared.thrift"  
  21.    
  22.    
  23. namespace cpp tutorial  
  24. namespace java tutorial  
  25. namespace php tutorial  
  26. namespace perl tutorial  
  27. namespace smalltalk.category Thrift.Tutorial  
  28.    
  29. typedef i32 MyInteger  
  30.    
  31. const i32 INT32CONSTANT = 9853  
  32. const map<string,string> MAPCONSTANT = {'hello':'world''goodnight':'moon'}  
  33.    
  34. enum Operation {  
  35.   ADD = 1,  
  36.   SUBTRACT = 2,  
  37.   MULTIPLY = 3,  
  38.   DIVIDE = 4  
  39. }  
  40.    
  41. struct Work {  
  42.   1: i32 num1 = 0,  
  43.   2: i32 num2,  
  44.   3: Operation op,  
  45.   4: optional string comment,  
  46. }  
  47.    
  48. exception InvalidOperation {  
  49.   1: i32 what,  
  50.   2: string why  
  51. }  
  52.    
  53. service Calculator extends shared.SharedService {  
  54.    
  55.    void ping(),  
  56.    
  57.    i32 add(1:i32 num1, 2:i32 num2),  
  58.    
  59.    i32 calculate(1:i32 logid, 2:Work w) throws (1:InvalidOperation ouch),  
  60.    
  61.    oneway void zip()  
  62.    
  63. }  
  64.   
  65. # 3. 我们来写个 helloworld.thrift  
  66.    
  67. service HelloWorld{  
  68.  string ping(1: string name),  
  69.  string getpng(),  
  70. }  
# 1.支持的变量类型 类型   描述  bool   #true, false  byte   #8位的有符号整数  i16    #16位的有符号整数  i32    #32位的有符号整数  i64    #64位的有符号整数  double   #64位的浮点数  string   #UTF-8编码的字符串  binary   #字符数组  struct   #结构体  list<type>  #有序的元素列表,类似于STL的vector  set<type>  #无序的不重复元素集,类似于STL的set  map<type1,type2> #key-value型的映射,类似于STL的map  exception  #是一个继承于本地语言的exception基类  service   #服务包含多个函数接口(纯虚函数)   # 2.摘一段例子上来,让瞧瞧这是啥东东。(本例子文件名为:tutorial.thrift,是本身带的教程。)include "shared.thrift"  namespace cpp tutorialnamespace java tutorialnamespace php tutorialnamespace perl tutorialnamespace smalltalk.category Thrift.Tutorial typedef i32 MyInteger const 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 what,  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() } # 3. 我们来写个 helloworld.thrift service HelloWorld{ string ping(1: string name), string getpng(),}
  1.    
 

三、编译 helloworld:

 

  1. /usr/local/thrift/bin/thrift -r --gen py helloworld.thrift  
  2. /usr/local/thrift/bin/thrift -r --gen php helloworld.thrift  
  3. #会在当前目录下生成 gen-* 目录。  
/usr/local/thrift/bin/thrift -r --gen py helloworld.thrift/usr/local/thrift/bin/thrift -r --gen php helloworld.thrift#会在当前目录下生成 gen-* 目录。

 

 
四、编写服务器端:
 
[python] view plain copy print ?
  1. import sys  
  2. sys.path.append('./gen-py')  
  3.    
  4. from helloworld import HelloWorld  
  5. from helloworld.ttypes import *  
  6.    
  7. from thrift.transport import TSocket  
  8. from thrift.transport import TTransport  
  9. from thrift.protocol import TBinaryProtocol  
  10. from thrift.server import TServer  
  11.    
  12. class HellowordHandler:  
  13.     def __init__ (self):  
  14.         pass  
  15.    
  16.     def ping (self, name):  
  17.         print name + ' from server.'  
  18.         return "%s from server." % name  
  19.     def getpng (self):  
  20.         f = open("./logo.png""rb")  
  21.         c = f.read()  
  22.         f.close()  
  23.         return c  
  24. handler = HellowordHandler()  
  25. processor = HelloWorld.Processor(handler)  
  26. transport = TSocket.TServerSocket(9090)  
  27. tfactory = TTransport.TBufferedTransportFactory()  
  28. pfactory = TBinaryProtocol.TBinaryProtocolFactory()  
  29.    
  30. server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)  
  31.    
  32. # You could do one of these for a multithreaded server  
  33. #server = TServer.TThreadedServer(processor, transport, tfactory, pfactory)  
  34. #server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory)  
  35.    
  36. print 'Starting the server...'  
  37. server.serve()  
  38. print 'done.'  
import syssys.path.append('./gen-py') from helloworld import HelloWorldfrom helloworld.ttypes import * from thrift.transport import TSocketfrom thrift.transport import TTransportfrom thrift.protocol import TBinaryProtocolfrom thrift.server import TServer class HellowordHandler: def __init__ (self):  pass  def ping (self, name):  print name + ' from server.'  return "%s from server." % name def getpng (self):  f = open("./logo.png", "rb")  c = f.read()  f.close()  return chandler = HellowordHandler()processor = HelloWorld.Processor(handler)transport = TSocket.TServerSocket(9090)tfactory = TTransport.TBufferedTransportFactory()pfactory = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) # You could do one of these for a multithreaded server#server = TServer.TThreadedServer(processor, transport, tfactory, pfactory)#server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory) print 'Starting the server...'server.serve()print 'done.'
 
 
五、编写客户端:
  1. <?php  
  2. try{  
  3.    
  4.     $GLOBALS['THRIFT_ROOT'] = './php/src';   
  5.     require_once $GLOBALS['THRIFT_ROOT'].'/Thrift.php';  
  6.     require_once $GLOBALS['THRIFT_ROOT'].'/protocol/TBinaryProtocol.php';  
  7.     require_once $GLOBALS['THRIFT_ROOT'].'/transport/TSocket.php';  
  8.     require_once $GLOBALS['THRIFT_ROOT'].'/transport/THttpClient.php';  
  9.     require_once $GLOBALS['THRIFT_ROOT'].'/transport/TBufferedTransport.php';  
  10.     error_reporting(E_NONE);  
  11.     $GEN_DIR = './gen-php';  
  12.     require_once $GEN_DIR.'/helloworld/HelloWorld.php';  
  13.     error_reporting(E_ALL);  
  14.    
  15.     $socket = new TSocket('*.*.*.*', 9090);  
  16.     $transport = new TBufferedTransport($socket, 1024, 1024);  
  17.     $protocol = new TBinaryProtocol($transport);  
  18.     $client = new HelloWorldClient($protocol);  
  19.    
  20.     $transport->open();  
  21.    
  22.     $a = $client->ping('xyq ');  
  23.     echo $a;  
  24.    
  25.     $transport->close();  
  26.    
  27.     } catch (TException $tx) {  
  28.         print 'TException: '.$tx->getMessage()."/n";  
  29.     }  
  30.    
  31. ?>  
<?phptry{  $GLOBALS['THRIFT_ROOT'] = './php/src';  require_once $GLOBALS['THRIFT_ROOT'].'/Thrift.php'; require_once $GLOBALS['THRIFT_ROOT'].'/protocol/TBinaryProtocol.php'; require_once $GLOBALS['THRIFT_ROOT'].'/transport/TSocket.php'; require_once $GLOBALS['THRIFT_ROOT'].'/transport/THttpClient.php'; require_once $GLOBALS['THRIFT_ROOT'].'/transport/TBufferedTransport.php'; error_reporting(E_NONE); $GEN_DIR = './gen-php'; require_once $GEN_DIR.'/helloworld/HelloWorld.php'; error_reporting(E_ALL);  $socket = new TSocket('*.*.*.*', 9090); $transport = new TBufferedTransport($socket, 1024, 1024); $protocol = new TBinaryProtocol($transport); $client = new HelloWorldClient($protocol);  $transport->open();  $a = $client->ping('xyq '); echo $a;  $transport->close();  } catch (TException $tx) {  print 'TException: '.$tx->getMessage()."/n"; } ?>

按上面的流程就可以写自己的thrift了,我使用py做服务端,用php做客户端,当然也可以使用c++来做服务端。

 

 

 

相关文章:

thrift 安装 http://wiki.apache.org/thrift/ThriftInstallation
redis + thrift + mongodb 数据测试 http://www.ys250.com/2010/09/02/redis-thrift-mongodb-test/
Thrift基本使用 http://hi.baidu.com/infant/blog/item/01fa53436adc79189313c69e.html

 

           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow
这里写图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
语言 RPC 框架 Thrift 是一个开源的高效通信协议和序列化框架,可以用于构建语言的客户端和服务器端应用程序。 下面是一个简单的 Thrift 实战示例: 1. 定义 Thrift 文件:首先,我们需要创建一个 .thrift 文件来定义我们的 RPC 接口和数据结构。例如,我们可以创建一个名为 "calculator.thrift" 的文件,其中包含以下内容: ``` namespace java com.example.calculator namespace py calculator service CalculatorService { i32 add(1: i32 num1, 2: i32 num2), i32 subtract(1: i32 num1, 2: i32 num2), i32 multiply(1: i32 num1, 2: i32 num2), double divide(1: double num1, 2: double num2) } ``` 2. 生成代码:使用 Thrift 编译器将 .thrift 文件生成相应语言的代码。例如,我们可以使用以下命令生成 Java 和 Python 的代码: ``` thrift --gen java calculator.thrift thrift --gen py calculator.thrift ``` 这将生成相应语言的客户端和服务器端代码。 3. 实现服务器端:在服务器端,我们需要实现 Thrift 定义的接口。对于 Java,我们可以编写一个实现 CalculatorService 接口的类,并在该类中实现具体的业务逻辑。对于 Python,我们可以编写一个类似的实现。 4. 启动服务器:在服务器上启动 Thrift 服务器,以便接受客户端的请求。不同语言服务器实现方式可能有所不同,但通常都需要提供一个监听指定端口的入口。 5. 实现客户端:在客户端,我们可以使用生成的客户端代码来调用服务器端的接口。对于 Java,我们可以创建一个 Thrift 客户端,并使用生成的代码来调用服务器端提供的方法。对于 Python,我们可以编写相应的客户端代码。 6. 运行客户端:运行客户端代码,通过网络连接到服务器,并发送请求调用服务器端的方法。 以上是一个简单的 Thrift 实战示例。请注意,具体的实现方式和步骤可能因语言和框架而异,但基本原理是相似的。Thrift 还支持更多高级特性,如异步调用、连接池等,可以根据具体需求进行扩展和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值