Thrift 简介与安装配置
本文简要介绍了如何利用 Python 构建一个简易的 Thrift 服务端与客户端测试环境。
一、简介
Thrift 是一款软件框架,旨在开发具备扩展性及跨语言特性的服务。它结合了强大的软件堆栈与代码生成引擎,能够在 C++、Java、Python、PHP、Ruby、Erlang、Perl、Haskell、C#、Cocoa、JavaScript、Node.js、Smalltalk 以及 OCaml 等多种编程语言之间实现无缝对接,提供高效的服务支持。
二、安装
1. 下载地址
http://www.apache.org/dyn/closer.cgi?path=/thrift/0.9.2/thrift-0.9.2.tar.gz
2. 安装步骤
[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
3. 安装 Python 插件
pip install thrift
三、准备服务器端
1. 编辑接口文件 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)
注:以上即为 Thrift 服务端与客户端的实现小案例。该方案通常应用于多种语言联合开发的场景;若仅使用单一语言,Thrift 的优势则不明显。在多语言协作中,获取其他语言生成的 thrift 文件后,可直接使用 Python 作为客户端调用其中的函数,或提供 thrift 服务端文件供其他语言调用。总体而言,这种方式十分便捷,希望上述示例能帮助读者理解 Thrift 的基本应用!