1、安装Thrift包
sudo pip install thrift
2、下载thrift.exe
从官网 上下载 windows 版的 thrift.exe:(我这里用的是0.9.3版本)
3、将thrift-0.9.3.exe改名为thrift.exe
4、编写一个简单接IDL文件helloworld.thrift
const string HELLO_WORLD = "world"
service HelloWorld {
void ping(),
string sayHello(),
string sayMsg(1:string msg)
}
5、执行thrift.exe(打开命令窗口将路径切换到thrift.exe和helloworld.thrift所在路径下在执行下述命令)
thrift -r --gen py helloworld.thrift
执行完成后生成gen-py文件夹
6、在工程目录thrift下新建一个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!")
7、在工程目录thrift下新建一个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_WORLD")
print(msg)
transport.close()
except Thrift.TException as tx:
print("%s" % (tx.message))
8、运行PythonServer,报错。
点击红色箭头处,加了个.
再次运行:
9、运行PythonClient,报错。
点击红色箭头处,加了个.
再次运行,成功!!