1. 安装
brew install thrift
pip install thrift
2. 编写thrift服务
helloworld.thrift
service HelloWorld {
string ping(),
string say(1:string msg)
}
3. 自动生成代码
执行以下命令:
thrift -gen py helloworld.thrift
它会在当前目录的gen
目录下生成以下文件:
├── gen-py
│ ├── __init__.py
│ └── helloworld
│ ├── HelloWorld-remote
│ ├── HelloWorld.py
│ ├── __init__.py
│ ├── constants.py
│ ├── ttypes.py
4. 编写server代码
server.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
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!"
5. 编写client代码
client.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
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)
Ref