Apache Thrift软件框架(用于可扩展的跨语言服务开发)将软件堆栈与代码生成引擎结合在一起,以构建可在C ++,Java,Python,PHP,Ruby,Erlang,Perl,Haskell,C#,可可,JavaScript,Node.js,Smalltalk,OCaml和Delphi等语言。
我们首先开启一个服务脚本,bind在本机上的一个未被占用端口,然后我们使用客户端的脚本连接服务脚本。
可以类比于C\S架构。
但是在RPC中,sever.py与client.py需要根据接口文件进行编写。也即在接口文件是在开发之前就已经编写好的。之后server.py和client.py都是要根据接口文件来进行开发。
RPC的文件结构大家已经清楚了,下面我们就开始嗨吧。
1. 下载thrift.exe.放在python/Script目录下
放在目录下后,运行cmd。如下图则说明成功,若有问题,则检查环境变量。
2.使用pip,安装thrift模块
python -m pip install thrift
3.编写接口文件。以.thrift后缀结尾。
rpc.schema.thirft
service MY_RPC{
string hello(),
bool export_alembic(1:string maya_file_path,2:string alembic_output_dir),
}
4.将接口文件生成python 模块:在文件夹搜索框中输入cmd,然后输入:
thrift --gen py rpc.schema.thirft
5.编写server.py. 步骤4中生成的模块需要导入server.py中:server.py代码如下图:
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
from rpc.schema import MY_RPC
class RPCHandle(object):
"""
"""
def __init__(self):
pass
def hello(self):
"""
:return:
"""
return "hello my friend"
def export_alembic(self, maya_file_path, alembic_output_dir):
print(f"export_alembic{maya_file_path} to {alembic_output_dir}")
return True
def main():
"""
:return:
"""
handler = RPCHandle()
processor = MY_RPC.Processor(handler)
transport = TSocket.TServerSocket(host='127.0.0.1', port=19090)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
server.serve()
if __name__ == '__main__':
main()
可以看到server的函数与接口文件中是对应的。在这里服务端就编写好了。
在文件夹输入cmd,然后输入python server.py 将服务打开
python server.py
6.编写client.py,客户端只需要根据接口文件连接服务端即可:
from rpc.schema import MY_RPC
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
def main():
# Make socket
transport = TSocket.TSocket('127.0.0.1', 19090)
# 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 = MY_RPC.Client(protocol)
# Connect!
transport.open()
print(client.hello())
print(client.export_alembic("C:\Windows\System32\\a.ma","C:\Windows\System32\maya.exe"))
transport.close()
if __name__ == '__main__':
main()
7.至此,服务脚本 客户端脚本已经完成,运行客户端即可完成与服务端的通信。