Python之RPC开发讲解第10篇:协议与传输选择,服务器

35 阅读1分钟

🚀🚀🚀本篇主要内容

协议与传输选择

1 协议

Thrift 可以让用户选择客户端与服务端之间传输通信的消息协议类别,如 前面所讲总体划分为文本 (text) 和二进制 (binary) ,为节约带宽,提高传输效率,一般情况下使用二进制类型的为多数,有时还会使用基于文本类型的协议,这需要根据项目 / 产品中的实际需求。常用协议有以下几种:

* thrift.protocol.TBinaryProtocol

二进制编码格式进行数据传输

客户端构建方式:

protocol = TBinaryProtocol.TBinaryProtocol(transport)

Python 标准库参考

服务端构建方式:

pfactory = TBinaryProtocol.TBinaryProtocolFactory()

服务器

Thrift提供的常见服务端类型有一下几种:

* thrift.server.TServer.TSimpleServer 单线程服务器 * thrift.server.TServer.TThreadedServer 多线程服务器 * thrift.server.TServer.TThreadPoolServer 线程池服务器 * thrift.server.TServer.TForkingServer 多进程服务器

以线程池服务器为例,其他方式相同。

import sys
sys.path.append('gen-py')  # 增加生成代码的查找包路径

from calculate import Calculate
from base.ttypes import InvalidOperation,