`
AILIKES
  • 浏览: 177983 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

thrift

阅读更多

一、About  thrift  
二、什么是thrift,怎么工作?
三、Thrift  IDL
四、Thrift   Demo
五、Thrift 协议栈 以及各层的使用(java 为例)
六、与protocolbuffer的区别

一、About  thrift  
         thrift是一种可伸缩的跨语言服务的发展软件框架。它结合了功能强大的软件堆栈的代码生成引擎,以建设服务,工作效率和无缝地与C + +,C#,Java,Python和PHP和Ruby结合。thrift是facebook开发的,我们现在把它作为开源软件使用。thrift允许你定 义一个简单的定义文件中的数据类型和服务接口。以作为输入文件,编译器生成代码用来方便地生成RPC客户端和服务器通信的无缝跨编程语言(来自百度百 科)。   
  >>>最初由facebook开发用做系统内个语言之间的RPC通信 。
  >>>2007年由facebook贡献到apache基金 ,现在是apache下的opensource之一 。
  >>>支持多种语言之间的RPC方式的通信:php语言client可以构造一个对象,调用相应的服务方法来调用java语言的服务 ,跨越语言的C/S   rpc  调用 。


二、什么是thrift,怎么工作?

java  rmi的例子,代码见附件,建立一个java rmi的流程  :
  >>>定义一个服务调用接口 。
  >>>server端:接口实现---impl的实例---注册该服务实现(端口)---启动服务。
  >>>client端:通过ip、端口、服务名,得到服务,通过接口来调用 。
  >>>rmi数据传输方式:java对象序列化 。

Thrift  服务 
  >>>例同rmi ,需要定义通信接口、实现、注册服务、绑定端口……
  >>>如何多种语言之间通信  ?
  >>>数据传输走socket(多种语言均支持),数据再以特定的格式(String ),发送,接收方语言解析   。
        Object --->  String --->  Object  。

    问题:编码、解析完全需要自己做 ,复杂的数据结构会编码困难 .


Thrift  服务 :thrift的中间编码层
  >>>java  Object ---> Thrift  Object ---> php  Object  
  >>> 定义thrift的文件 ,由thrift文件(IDL)生成 双方语言的接口、model ,在生成的model以及接口中会有解码编码的代码 。
  >>>thrift   文件例子
     thrift-0.7.0.exe   -r   -gen  java    TestThrift.thrift    生成java 代码
     thrift-0.7.0.exe   -r   -gen  php    TestThrift.thrift    生成php代码
     thrift-0.7.0.exe   -r   -gen  py       TestThrift.thrift    生成python代码
     thrift-0.7.0.exe   -r   -gen  as3     TestThrift.thrift    生成as3代码
     thrift-0.7.0.exe   -r   -gen  cpp     TestThrift.thrift    生成C++代码

三、Thrift  IDL
                
       http://www.cnblogs.com/tianhuilove/archive/2011/09/05/2167669.html

       http://wiki.apache.org/thrift/
          
       http://wiki.apache.org/thrift/ThriftTypes

四、Thrift   Demo
Thrift  IDL 文件

Java代码  收藏代码
  1. namespace java com.gemantic.analyse.thrift.index  
  2.   
  3. struct  NewsModel{  
  4. 1:i32 id ;  
  5. 2:string title;  
  6. 3:string content;  
  7. 4:string media_from;  
  8. 5:string author;  
  9. }  
  10.   
  11. service IndexNewsOperatorServices {  
  12. bool indexNews(1:NewsModel indexNews),  
  13. bool deleteArtificiallyNews(1:i32 id )  
  14. }  



java  server

Java代码  收藏代码
  1. package com.gemantic.analyse.thrift.index;  
  2.   
  3. import java.net.InetSocketAddress;  
  4.   
  5. import org.apache.thrift.protocol.TBinaryProtocol;  
  6. import org.apache.thrift.server.TServer;  
  7. import org.apache.thrift.server.TThreadPoolServer;  
  8. import org.apache.thrift.server.TThreadPoolServer.Args;  
  9. import org.apache.thrift.transport.TServerSocket;  
  10. import org.apache.thrift.transport.TServerTransport;  
  11. import org.apache.thrift.transport.TTransportFactory;  
  12.   
  13. public class ThriftServerTest {  
  14.   
  15.     /** 
  16.      * @param args 
  17.      */  
  18.     public static void main(String[] args) {  
  19.         // TODO Auto-generated method stub  
  20.         IndexNewsOperatorServices.Processor processor = new IndexNewsOperatorServices.Processor(new IndexNewsOperatorServicesImpl());  
  21.         try{  
  22.             TServerTransport serverTransport = new TServerSocket( new InetSocketAddress("0.0.0.0",9813));  
  23.             Args trArgs=new Args(serverTransport);  
  24.             trArgs.processor(processor);  
  25.             //使用二进制来编码应用层的数据  
  26.             trArgs.protocolFactory(new TBinaryProtocol.Factory(truetrue));  
  27.             //使用普通的socket来传输数据  
  28.             trArgs.transportFactory(new TTransportFactory());  
  29.             TServer server = new TThreadPoolServer(trArgs);  
  30.             System.out.println("server begin ......................");  
  31.             server.serve();  
  32.             System.out.println("---------------------------------------");  
  33.             server.stop();  
  34.         }catch(Exception e){  
  35.             throw new RuntimeException("index thrift server start failed!!"+"/n"+e.getMessage());  
  36.         }  
  37.     }  
  38.   
  39. }  



java client

Java代码  收藏代码
  1. package com.gemantic.analyse.thrift.index;  
  2.   
  3. import org.apache.thrift.TException;  
  4. import org.apache.thrift.protocol.TBinaryProtocol;  
  5. import org.apache.thrift.protocol.TProtocol;  
  6. import org.apache.thrift.transport.TSocket;  
  7. import org.apache.thrift.transport.TTransport;  
  8.   
  9. public class ThriftClientTest {  
  10.   
  11.     /** 
  12.      * @param args 
  13.      * @throws TException  
  14.      */  
  15.     public static void main(String[] args) throws TException {  
  16.         // TODO Auto-generated method stub  
  17.         TTransport transport = new TSocket("10.0.0.41"9813);  
  18.         long start=System.currentTimeMillis();  
  19. //      TTransport transport = new TSocket("218.11.178.110",9090);  
  20.         TProtocol protocol = new TBinaryProtocol(transport);  
  21.         IndexNewsOperatorServices.Client client=new IndexNewsOperatorServices.Client(protocol);  
  22.         transport.open();  
  23.   
  24.           
  25.         client.deleteArtificiallyNews(123456);  
  26.         NewsModel newsModel=new NewsModel();  
  27.         newsModel.setId(789456);  
  28.         newsModel.setTitle("this from java client");  
  29.         newsModel.setContent(" 世界杯比赛前,由于塞尔维亚和黑山突然宣布分裂,国际足联开会决定剔除塞黑,由世界上球迷最多的国家顶替,名额恰巧来到中国。举国上下一片欢腾,中国足协决定由“成世铎”(成龙+阎世铎)组队,进军世界杯。");  
  30.         newsModel.setAuthor("ddc");  
  31.         newsModel.setMedia_from("新华08");  
  32.         client.indexNews(newsModel);  
  33.         transport.close();  
  34.         System.out.println((System.currentTimeMillis()-start));  
  35.         System.out.println("client sucess!");  
  36.     }  
  37.   
  38. }  



php client

Php代码  收藏代码
  1. <?php  
  2. $GLOBALS['THRIFT_ROOT'] = '/home/tjiang/demo/thrift/lib/php/src';  
  3. require_once $GLOBALS['THRIFT_ROOT'].'/Thrift.php';  
  4. require_once $GLOBALS['THRIFT_ROOT'].'/protocol/TBinaryProtocol.php';  
  5. require_once $GLOBALS['THRIFT_ROOT'].'/transport/TSocket.php';  
  6. require_once $GLOBALS['THRIFT_ROOT'].'/transport/THttpClient.php';  
  7. require_once $GLOBALS['THRIFT_ROOT'].'/transport/TBufferedTransport.php';  
  8. include_once $GLOBALS['THRIFT_ROOT'].'/packages/TestThrift/TestThrift_types.php';  
  9. include_once $GLOBALS['THRIFT_ROOT'].'/packages/TestThrift/IndexNewsOperatorServices.php';  
  10. $data=array(  
  11. 'id'=>'1',  
  12. 'title'=>'demo-标题',  
  13. 'content'=>'demo-内容',  
  14. 'media_from'=>'hexun',  
  15. 'author'=>'xiaodi667'  
  16. );  
  17. $thrif_server_url = '10.0.0.41';  
  18. $transport = new TSocket($thrif_server_url, 9813);  
  19. $transport->open();  
  20.   
  21. $protocol = new TBinaryProtocol($transport);  
  22.   
  23. $clientnew IndexNewsOperatorServicesClient($protocol$protocol);  
  24. $obj = new NewsModel($data);  
  25. $result = $client->indexNews($obj);  
  26.   
  27. $transport->close();  
  28. ?>  



python client

Python代码  收藏代码
  1. #!/usr/bin/env python  
  2.   
  3. #  
  4. # Licensed to the Apache Software Foundation (ASF) under one  
  5. # or more contributor license agreements. See the NOTICE file  
  6. # distributed with this work for additional information  
  7. # regarding copyright ownership. The ASF licenses this file  
  8. # to you under the Apache License, Version 2.0 (the  
  9. # "License"); you may not use this file except in compliance  
  10. # with the License. You may obtain a copy of the License at  
  11. #  
  12. #   http://www.apache.org/licenses/LICENSE-2.0  
  13. #  
  14. # Unless required by applicable law or agreed to in writing,  
  15. # software distributed under the License is distributed on an  
  16. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY  
  17. # KIND, either express or implied. See the License for the  
  18. # specific language governing permissions and limitations  
  19. # under the License.  
  20. #  
  21.   
  22. import sys  
  23.   
  24. from TestThrift.ttypes import NewsModel  
  25. from TestThrift.IndexNewsOperatorServices import Client  
  26.   
  27. from thrift import Thrift  
  28. from thrift.transport import TSocket  
  29. from thrift.transport import TTransport  
  30. from thrift.protocol import TBinaryProtocol  
  31.   
  32. try:  
  33.   
  34.   # Make socket  
  35.   transport = TSocket.TSocket('10.0.0.41'9813)  
  36.   
  37.   # Buffering is critical. Raw sockets are very slow  
  38.   transport = TTransport.TBufferedTransport(transport)  
  39.   
  40.   # Wrap in a protocol  
  41.   protocol = TBinaryProtocol.TBinaryProtocol(transport)  
  42.   
  43.   # Create a client to use the protocol encoder  
  44.   client = Client(protocol)  
  45.   
  46.   # Connect!  
  47.   transport.open()  
  48.   
  49.   client.deleteArtificiallyNews(123)  
  50.     
  51.   newsModel=NewsModel()  
  52.   newsModel.id=123456  
  53.   newsModel.title="python Test"  
  54.   newsModel.content="client test  come from python";  
  55.   newsModel.media_from="xinhua08"  
  56.     
  57.   client.indexNews(newsModel)  
  58.     
  59.   #close  
  60.   transport.close()  
  61. except Thrift.TException, tx:  
  62.   print '%s' % (tx.message)  



Csharp client

C#代码  收藏代码
  1. TTransport transport = new TSocket("10.0.0.41", 9813);  
  2. TProtocol protocol = new TBinaryProtocol(transport);  
  3. IndexNewsOperatorServices.Client client = new IndexNewsOperatorServices.Client(protocol);  
  4.   
  5. transport.Open();  
  6. NewsModel model = new NewsModel();  
  7. model.Author = "jww";  
  8. model.Title = "title";  
  9. model.Content = "client   Come   From   CSharp";  
  10. model.Id = 1;  
  11.   
  12. client.deleteArtificiallyNews(123);  
  13. Console.WriteLine(client.indexNews(model));  




五、Thrift 协议栈 以及各层的使用(java 为例)

1、model   interface
       服务的调用接口以及接口参数model、返回值model
2、Tprotocol    协议层
         将数据(model)编码 、解码 。
3、Ttramsport 传输层
        编码后的数据传输(简单socket、http)
5、Tserver
        服务的Tserver类型,实现了几种rpc调用(单线程、多线程、非阻塞IO)

六、与protocolbuffer的区别
http://liuchangit.com/development/346.html
           
http://stackoverflow.com/questions/69316/biggest-differences-of-thrift-vs-protocol-buffers

区别:
1、Another important difference are the languages supported by default.    protobuf: Java, C++, Python    Thrift: Java, C++, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, Smalltalk, Ocaml
支持语言不同,thrift支持着更多的语言 。
2、Thrift supports ‘exceptions 。
   thrift支持服务的异常 。
3、Protocol Buffers much easier to read 。Protobuf API looks cleaner, though the generated classes are all packed as an inner classes which is not so nice.
   Protocol Buffers 在文档方面比thrift丰富,而且比thrift简单 。
4、Protobuf serialized objects are about 30% smaller then Thrift.
   Protocol Buffers在序列化/反序列化、传输上性能更优 。
5、RPC is another key difference. Thrift generates code to implement RPC clients and servers wheres Protocol Buffers seems mostly designed as a data-interchange format alone. 
    thrift提供了一套完整的rpc服务实现(多线程socket、非阻塞的socket....)
6、And according to the wiki the Thrift runtime doesn't run on Windows.
   thrift 对有些语言在windows上不支持:C++   .....

分享到:
评论

相关推荐

    the programmer's guide to apache thrift

    Apache Thrift is an open source cross language serialization and RPC framework. With support for over 15 programming languages, Apache Thrift can play an important role in a range of distributed ...

    thrift-0.9.3.exe

    Thrift是一个软件框架,用来进行可扩展且跨语言的服务的开发。它结合了功能强大的软件堆栈和代码生成引擎,以构建在 C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, ...

    用C#和C++写的Apache Thrift的小范例

    本例改编自Apache Thrift教程: http://mikecvet.wordpress.com/2010/05/13/apache-thrift-tutorial-the-sequel/ http://chanian.com/2010/05/13/thrift-tutorial-a-php-client/ 原教程使用的是c++ server和...

    Learning.Apache.Thrift.178588274

    Make applications cross-communicate using Apache Thrift! About This Book Leverage Apache Thrift to enable applications written in different programming languages (Java, C++, Python, PHP, Ruby, and so...

    Windows下QT使用Thrift的样例

    网上一直搜不到Windows下QT使用thrift的例子,自己整了个 QT版本 5.8.0 Boost版本 boost_1_61_0 Thrift版本 thrift-0.10.0

    使用wireshark抓取thrift协议接口调用

    使用wireshark抓取thrift协议接口调用

    thrift-0.9.2.tar.gz

    thrift,Apache Thrift 0.9.2 版本,解压后直接直接安装,可伸缩的跨语言服务开发框架,命令: 解压命令:tar -zxf thrift-0.9.2.tar.gz 安装命令:./configure --with-lua=no && make && make install 查看版本:...

    thrift-0.10.0.exe

    Thrift是一个软件框架,用来进行可扩展且跨语言的服务的开发。它结合了功能强大的软件堆栈和代码生成引擎,以构建在 C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, ...

    Thrift之C++初体验

    thrift是一个软件框架,用来进行可扩展且跨语言的服务的开发。它结合了功能强大的软件堆栈和代码生成引擎,以构建在 C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, ...

    java代码使用thrift2操作hbase示例

    java代码使用thrift2操作hbase示例,thrift2连接hbase添加数据,单条查找,删除数据,根据扫描器查找,修改数据等测试实例

    thrift环境搭建(内附thrift运行环境可执行程序、搭建说明文本)

    thrift环境搭建(内附thrift运行环境可执行程序、搭建说明文本)

    Thrift RPC客户端的服务化框架代码

    Thrift RPC客户端的服务化框架代码,

    thrift 源码(一种可伸缩的跨语言服务的发展软件框架)

    thrift是一种可伸缩的跨语言服务的发展软件框架。它结合了功能强大的软件堆栈的代码生成引擎,以建设服务,工作效率和无缝地与C + +,C#,Java,Python和PHP和Ruby结合。thrift是facebook开发的,我们现在把它作为...

    thrift-0.10.0.tar.gz

    Thrift是一个软件框架,用来进行可扩展且跨语言的服务的开发。它结合了功能强大的软件堆栈和代码生成引擎,以构建在 C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, ...

    thrift环境配置方法

    thrift 环境配置方法,步骤,顺序,只有文档,里面的方法很详细

    使用thrift、websocket在javascript和cpp之间建立rpc调用

    使用thrift、websocket在javascript和c++之间建立rpc调用机制。 如果要使用js+html来写界面,cpp来写底层业务逻辑,这就非常有用了。 当然,如果底层不用cpp来写,也可以参考本代码的js对thrift的rpc包装。

    thrift-编译工具

    thrift-编译工具

    zookeeper + thrift实现的RPC 服务治理框架演示

    这个示例工程和我的博客《架构设计:系统间通信(13)——RPC实例Apache Thrift 下篇》(http://blog.csdn.net/yinwenjie/article/details/49869535)相对应。相关的设计和代码说明,请参见我的博客。另外,工程已经...

    thrift文件生成工具thrift-generator.zip

    thrift-generator 是通过 Java 的接口生成 thrift 文件的工具。例子:public interface ICommonUserService {  public User login(int id, String name);  public User getUserById(long id);  ...

    基于thrift的RPC调用实例

    RPC(Remote Procedure Call Protocol)远程过程调用协议实例,学习和使用thrift无痛入门代码。具体使用方法,可以看博客详解。

Global site tag (gtag.js) - Google Analytics