Apache Thrift 是主流的PRC框架之一
1,最初是由 facebook 实现的一种支持多种编程语言的,高效的远程服务器框架
2,它采用中间语言(IDL,接口描述语言),定义PRC接口和数据类型,通过编译器生成不同的代码(python,java,C++,Ruby)等
3,其传输数据采用的是二进制数据.相对于XML与JSON体积更小,相对于高并发更加具优势
一,安装 thrift
sudo apt-get install libboost-dev libboost-test-dev libboost-program-options-dev libevent-dev automake libtool flex bison pkg-config g++ libssl-dev
下载/安装 thrift 软件
wget http://mirrors.hust.edu.cn/apache/thrift/0.11.0/thrift-0.11.0.tar.gz
tar zxf thrift-0.11.0.tar.gz
cd thrift-0.11.0/
make && sudo make install # 编译与安装!
thrift -version # 产看是否安装成功
新建文件 demo_thrift.thrift
service HelloWhat{
string hello_x(1:string what)
}
命令行 生成 thrift 项目
thrift --gen py demo_thrift.thrift
编辑client.py
from thrift.transport import TSocket
from thrift.protocol import TBinaryProtocol
from demo_thrift.demo.HelloWhat import *
def run():
try:
transport = TSocket.TSocket('localhost',9234)
# 选择 传输层!
transport = TTransport.TBufferedTransport(transport)
# 选择一个协议! 与上都要与服务器保持相同!
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = Client(protocol)
transport.open()
res = client.hello_x("Thrift")
res_second = client.hello_x("thrift again")
print(res_second)
print(res)
# 只要没有关闭 可以随时调用多次 client.hello_x()
transport.close()
except Exception as e:
print(e)
if __name__ == '__main__':
run()
编辑server.py
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
from thrift.transport import TSocket
from demo_thrift.demo.HelloWhat import *
class HelloHander:
def hello_x(self,what):
print('hello_x was called!')
return "hello %s!"%what
def run():
header =HelloHander()
pross = Processor(header)
# 监听端口
tran = TSocket.TServerSocket('localhost', 9234)
# 选择传输层
tfac = TTransport.TBufferedTransportFactory()
# 选择传输层协议
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TThreadPoolServer(
pross,tran,tfac,pfactory
)
server.setNumThreads(5)
print('server is begin')
server.serve()
if __name__ == '__main__':
run()
运行 server.py 运行 client.py