Python 使用 thrift教程; Mac(Windows)安装 thrift
本文转载自python 使用 thrift 教程
一、前言
Thrift 是一种接口描述语言和二进制通信协议。一些微服务可以通过Thrift进行通信。
Thrift 最初由FaceBook研发,主要用于各个服务之间的RPC通信,支持跨语言;简单的说,就是可以让人快速的写Socket Server(服务器)和Client(客户端)。其实不用Thrift开发socket也不难,那么为什么要用Thrift开发呢?主要有两个原因,一个是因为Thrift本身帮你封装了很多基本的东西,你不需要自己去写socket里面的bind,accept之类的,以及他们的逻辑。可以很快速的开发基于进程的,线程的,SSL的socket。第二个理由是标准化,跨语言和跨平台,Windows不算在其中。主要是在各种POSIX兼容的操作系统中都可以不需要改造基本直接可用,支持的语言种类也很多。类似的项目还有ICE和Avro,但是感觉都没有Thrift做的易用性好。
使用thrift需要先定义接口文件,在Thrift里简称叫IDL,全称叫Interface Description Language,接口描述语言。接口描述语言里面需要定义接口中所使用的数据类型,方法等等。
需要定义一个xxx.thrift的文件,来生成各种语言的代码,生成之后我们的服务提供者和消费者,都需要把代码引入,服务端把代码实现,消费者直接使用API的存根,直接调用。
和 http 相比,同属于应用层,走 tcp 协议。Thrift 优势在于发送同样的数据,request 包和 response 包要比http小很多,在整体性能上要优于 http。
二、使用方法
环境准备:
Mac:
-
第一步:使用 brew 命令给电脑安装 Thrift
brew install thrift
-
第二步:pip安装Thrift
pip3 install thrift
Windows:
- 从官网上下载 windows 版的 thrift.exe:http://www.apache.org/dyn/closer.cgi?path=/thrift/0.12.0/thrift-0.12.0.exe
- python版本:Python 3.7.1
- pip3 install thrift
1、首先使用 Thrift 之前需要定义一个 .thrift 格式的文件,比如 test.thrift:
service Transmit {
string sayMsg(1:string msg);
string invoke(1:i32 cmd 2:string token 3:string data)
}
然后运行命令:thrift -gen py test.thrift
生成 Python 代码
生成如下结构:
2、然后将生成的 Python 代码和文件,放到新建的 Python 项目中。完成后先运行服务器代码。
服务端代码:server.py
import json
from test import Transmit
from test.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("sayMsg(" + msg + ")")
return "say " + 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', 8000)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
print("Starting python server...")
server.serve()
客户端代码 client.py
import sys
import jsonfrom test import Transmit
from test.ttypes import *
from test.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', 8000)
transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = Transmit.Client(protocol)
# Connect!
transport.open()
cmd = 2
token = '1111-2222-3333-4444'
data = json.dumps({"name":"zhoujielun"})
msg = client.invoke(cmd,token,data)
print(msg)
transport.close()
# 执行结果:
# cmd不匹配
本文转载自python 使用 thrift 教程