参考
thrift 是rpc协议
python 使用 thrift 教程
1 安装
1.1 mac os
# 执行下面,更新homebrew
➜ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
# 安装thrift
➜ brew install thrift
# 安装成功
➜ ~ thrift -version
Thrift version 0.14.1
2 使用
2.1 thrift生成python模块
由于python语法最简单,此种先以python演示
目录: ~/mythrift , 创建hello.thrift 文件
// 创建hello.thrift
service Transmit
{
string sayMsg(1: string msg)
}
//终端下执行thrift命令
thrift -gen py hello.thrift //生成python的命令,产出gen-py文件夹
thrift -r --gen php:server hello.thrift //生成php的命令,产出gen-php文件夹
//gen-py文件夹的树形结构,生成了hello模块
➜ gen-py tree
.
├── __init__.py
└── hello
├── Transmit-remote
├── Transmit.py
├── __init__.py
├── constants.py
└── ttypes.py
2.2 使用模块实现rpc调用
python使用thrirft要先安装thrift模块
pip install thrift
服务端代码 gen-py/testThriftServer.py.:
import json
from hello import Transmit
from hello.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 TransmitHandler:
def __init__(self):
self.log = {}
def sayMsg(self, msg):
msg = json.loads(msg)
print("sayMsy(" + str(msg) + ")")
return "say: " + str(msg) + " from " + socket.gethostbyname(socket.gethostname())
def invoke(self,cmd,token,data):
cmd = cmd
token =token
data = data
if cmd ==1:
return json.dumps({token:data})
else:
return 'cmd不匹配'
if __name__ == "__main__":
handler = TransmitHandler()
processor = Transmit.Processor(handler)
transport = TSocket.TServerSocket('127.0.0.1',8088)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TSimpleServer(processor,transport,tfactory,pfactory)
print("starting python server")
server.serve()
客户端gen-py/testThriftClient.py
import sys
import json
from hello import Transmit
from hello.ttypes import *
from hello.constants import *
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
transport = TSocket.TSocket('127.0.0.1', 8088)
transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = Transmit.Client(protocol)
# Connect!
transport.open()
cmd = 1
token = '1111-2222-3333-4444'
data = json.dumps({"name":"zhoujielun"})
# msg = client.sayMsg(data)
new_msg = client.sayMsg(data)
msg = client.invoke(cmd,token,data)
print(msg)
print(new_msg)
transport.close()
执行:
# 1 先运行服务端
➜ gen-py python3 testThriftServer.py
starting python server
# 3 执行client后输出下面
sayMsy({'name': 'zhoujielun'})
# 2执行client端
➜ gen-py python3 testThriftClient.py
{"1111-2222-3333-4444": "{\"name\": \"zhoujielun\"}"}
say: {'name': 'zhoujielun'} from 127.0.0.1