thrift是一个软件框架,用来进行可扩展且跨语言的服务的开发。它结合了功能强大的软件堆栈和代码生成引擎,以构建在 C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, and OCaml 这些编程语言间无缝结合的、高效的服务。python
http://www.apache.org/dyn/closer.cgi?path=/thrift/0.9.2/thrift-0.9.2.tar.gz
[root@localhost ~]# yum -y groupinstall "Development Tools" [root@localhost ~]# yum -y install libevent-devel zlib-devel openssl-devel autoconf automake [root@localhost ~]# wget http://ftp.gnu.org/gnu/bison/bison-2.5.1.tar.gz [root@localhost ~]# tar xf bison-2.5.1.tar.gz [root@localhost ~]# cd bison-2.5.1 [root@localhost ~]# ./configure --prefix=/usr [root@localhost ~]# make [root@localhost ~]# make install [root@localhost ~]# tar xf thrift-0.9.2.tar.gz [root@localhost ~]# cd thrift-0.9.2 [root@localhost thrift-0.9.2]# ./configure -with-lua=no
pip install thrift
helloworld.thrift
:#!/usr/bin/env python import socket import sys sys.path.append('./gen-py') from helloworld import HelloWorld from helloworld.ttypes import * from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from thrift.server import TServer class HelloWorldHandler: def ping(self): return "pong" def say(self, msg): ret = "Received: " + msg print ret return ret #建立服务端 handler = HelloWorldHandler() processor = HelloWorld.Processor(handler) #监听端口 transport = TSocket.TServerSocket("localhost", 9090) #选择传输层 tfactory = TTransport.TBufferedTransportFactory() #选择传输协议 pfactory = TBinaryProtocol.TBinaryProtocolFactory() #建立服务端 server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) print "Starting thrift server in python..." server.serve() print "done!"
#!/usr/bin/env python import sys sys.path.append('./gen-py') from helloworld import HelloWorld #引入客户端类 from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol try: #创建socket transport = TSocket.TSocket('localhost', 9090) #选择传输层,这块要和服务端的设置一致 transport = TTransport.TBufferedTransport(transport) #选择传输协议,这个也要和服务端保持一致,不然没法通讯 protocol = TBinaryProtocol.TBinaryProtocol(transport) #建立客户端 client = HelloWorld.Client(protocol) transport.open() print "client - ping" print "server - " + client.ping() print "client - say" msg = client.say("Hello!") print "server - " + msg #关闭传输 transport.close() #捕获异常 except Thrift.TException, ex: print "%s" % (ex.message)
PS.这个就是thrift的服务端和客户端的实现小案例。通常只有在多种语言联合开发时才会用到,若是是一种语言的话,thrift就没有用武之地了。在多语言开发时,咱们拿到其余语言的thrift文件,就能够直接使用咱们的python做为客户端去调用thrift中的函数就能够了,或者咱们提供thrift服务端文件供别的语言调用,总起来讲仍是很方便的,但愿上面的例子可让你们明白thrift的简单应用!apache