1、下载thrift,下载地址:http://archive.apache.org/dist/thrift/0.9.3/
2、在编写python的thrift代码时,需要先安装thrift module,下载路径:https://pypi.python.org/pypi/thrift/0.9.1
3、安装thrift:在C盘新建一个Thtift文件夹,将下载的thrift-0.9.3.exe重新命名为thrift.exe后放到Thtift文件夹下,将该路径添加到环境变量,检验是否安装成功:在命令行中输入:
即可以看到安装后的版本信息。
4、thrift 采用IDL(Interface Definition Language)来定义通用的服务接口,并通过生成不同的语言代理实现来达到跨语言、平台的功能。在thrift的IDL中可以定义以下一些类型:基本数据类型,结构体,容器,异常、服务。
thrift脚本:
const string HELLO_YK = "yk"
service HelloWorld {
void ping(),
string sayHello(),
string sayMsg(1:string msg)
}
thrift脚本通过Thrift编辑器生成所要求的python开发语言代码。即:
5、Thrift是一个典型的CS结构,客户端和服务端可以使用不同的语言开发。本文以python为例:
PythonServer.py:
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 import socket class HelloWorldHandler: def __init__(self): self.log = {} def ping(self): print "ping()" def sayHello(self): print "sayHello()" return "say hello from " + socket.gethostbyname(socket.gethostname()) def sayMsg(self, msg): print "sayMsg(" + msg + ")" return "say " + msg + " from " + socket.gethostbyname(socket.gethostname()) handler = HelloWorldHandler() processor = HelloWorld.Processor(handler) transport = TSocket.TServerSocket('127.0.0.1',30303) tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) print "Starting python server..." server.serve() print "done!"
PythonClient.py
import sys sys.path.append('./gen-py') from helloworld import HelloWorld from helloworld.ttypes import * from helloworld.constants import * from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol try: # Make socket transport = TSocket.TSocket('127.0.0.1', 30303) # 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 = HelloWorld.Client(protocol) # Connect! transport.open() client.ping() print "ping()" msg = client.sayHello() print msg msg = client.sayMsg(HELLO_YK) print msg transport.close() except Thrift.TException, tx: print "%s" % (tx.message)
运行结果:
文件下载:
作者:禅在心中
出处:http://www.cnblogs.com/pinking/
本文版权归作者和博客园共有,欢迎批评指正及转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。