Thrift的服务器和客户端Python案例
【摘要】
服务器
Thrift提供的常见服务端类型有一下几种:
thrift.server.TServer.TSimpleServer 单线程服务器thrift.server.TServer.TThreadedServer 多线程服务器thrift.server.TServer.TThreadPoolServer ...
服务器
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, Operation
-
-
from thrift.transport import TSocket
-
from thrift.transport import TTransport
-
from thrift.protocol import TCompactProtocol
-
from thrift.server import TServer
-
-
-
class CalculateHandler(Calculate.Iface):
-
"""被调用方法的具体实现"""
-
def ping(self):
-
print('ping()')
-
-
def divide(self, num1, num2):
-
if num2 == 0:
-
raise InvalidOperation(0, 'Cannot divide by 0')
-
return num1 / num2
-
-
def calculate(self, work):
-
if work.op == Operation.ADD:
-
val = work.num1 + work.num2
-
elif work.op == Operation.SUBTRACT:
-
val = work.num1 - work.num2
-
elif work.op == Operation.MULTIPLY:
-
val = work.num1 * work.num2
-
else:
-
raise InvalidOperation(work.op, 'Invalid operation')
-
return val
-
-
-
if __name__ == '__main__':
-
handler = CalculateHandler()
-
processor = Calculate.Processor(handler)
-
transport = TSocket.TServerSocket(host='127.0.0.1', port=8888)
-
tfactory = TTransport.TBufferedTransportFactory()
-
pfactory = TCompactProtocol.TCompactProtocolFactory()
-
-
server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory)
-
server.serve()
-
print('服务器已启动')
客户端
-
import sys
-
sys.path.append('gen-py')
-
-
from calculate import Calculate
-
from base.ttypes import InvalidOperation, Operation, Work
-
-
from thrift.transport import TSocket
-
from thrift.transport import TTransport
-
from thrift.protocol import TCompactProtocol
-
-
-
def main():
-
transport = TSocket.TSocket('127.0.0.1', 8888)
-
-
# 使用缓存传输
-
transport = TTransport.TBufferedTransport(transport)
-
-
# 使用压缩的二进制消息协议
-
protocol = TCompactProtocol.TCompactProtocol(transport)
-
-
client = Calculate.Client(protocol)
-
-
# 连接
-
transport.open()
-
-
client.ping()
-
print('ping()')
-
-
result = client.divide(100, 50)
-
print('100/50={}'.format(result))
-
-
try:
-
result = client.divide(100, 0)
-
except InvalidOperation as e:
-
print(e.why)
-
-
work = Work(1, 2, Operation.ADD)
-
result = client.calculate(work)
-
print('1+2={}'.format(result))
-
-
work = Work(15, 10, Operation.SUBTRACT)
-
result = client.calculate(work)
-
print('15-10={}'.format(result))
-
-
# 关闭
-
transport.close()
-
-
-
if __name__ == '__main__':
-
main()
文章来源: lansonli.blog.csdn.net,作者:Lansonli,版权归原作者所有,如需转载,请联系作者。
原文链接:lansonli.blog.csdn.net/article/details/105304671
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)