thrift最先由facebook开发,后来贡献给了apache。thrift主要解决跨语言调用的问题。php
thrift和protobuf,都解决了一个问题就是夸语言数据结构的定义,json也解决了跨语言的数据结构定义,只不过json都是字符串的,传输的开销和解析的开销可能有些大。那么想传输二进制的话怎么办呢,能够本身定义数据结构,好比你们熟知的网络协议就是这么定出来的,前1个字节表明啥啥啥,第二个字节表明啥啥啥,而后客户端和服务端都遵照这个协议。在没有thrift或者profobuf以前好多cs程序就是这么干的。可是这么干很累啊,还得写文档,并且开发时候也很差记,很差交流。后来人们想出了个办法,就是用一个相似json格式的文件定义数据结构,而后自动生成代码去处理二进制的转换,这样人们既能够用好读的格式定义数据结构,又能够高效的使用,因而就诞生了protobuf和thrift这类东西。protobuf到此为止了,thrift又把服务端程序和客户端程序也顺手加进去能够自动生成了,这样程序员就只负责写业务逻辑,其余的传输啊神马的都自动生成了,这就是protobuf和thrift的区别。这样thrift就有了全套的RPC机制,java
有人认为是团队须要,不一样的人擅长不一样的语言,我认为从架构的角度想,有2点好处python
是的,能够用json,好多api都是用json形式的,如今也流行REST,其实也是蛮方便的,可是有几个缺点linux
thrift的安装分两部分程序员
这个其实不必编译安装的,直接下载windows版的就行。 在linux上编译安装也还比较好装,可是可能会缺这缺那,缺啥用yum装便可算法
./configure make make install
语言包都在源码的lib目录下,因此下载linux版本才有,windows版本那个只是个编译好的thrift编译器apache
好比javajson
cd thrift源码/lib/java ant 会生成libthrift-0.9.3.jar
再好比pythonwindows
cd thrift源码/lib/py python setup.py install
service HelloService{ string sayHello(1:string username) }
而后用thrift编译:api
import org.apache.thrift.TException; public class helloImp implements HelloService.Iface { @Override public String sayHello(String username) throws TException { System.out.println(username); return username; } }
这里这个HelloService就是thrift生成的java文件 3. 写服务端
import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.server.TServer; import org.apache.thrift.server.TSimpleServer; import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TTransportException; public class Server { public void start() { TProcessor tpProcessor = new HelloService.Processor<HelloService.Iface>(new helloImp()); TServerSocket serverTransport; try { serverTransport = new TServerSocket(8889); TServer.Args args = new TServer.Args(serverTransport); args.processor(tpProcessor); args.protocolFactory(new TBinaryProtocol.Factory()); TServer server = new TSimpleServer(args); System.out.println("thrift server start"); server.serve(); } catch (TTransportException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { Server server = new Server(); server.start(); } }
4.写客户端 以python为列子
import sys import glob from hello import HelloService from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol # Make socket transport = TSocket.TSocket('localhost', 8889) # Buffering is critical. Raw sockets are very slow transport = TTransport.TBufferedTransport(transport) # Wrap in a protocol protocol = TBinaryProtocol.TBinaryProtocol(transport) # Create a client to use the protocol encoder client = HelloService.Client(protocol) # Connect! transport.open() rs = client.sayHello('luyu') print rs
其余语言版本怎么写????
在源码的tutorial目录下有各类语言的例子
持续更新 未完待续...