《精通并发与Netty》学习笔记(07 - 基于Thrift实现Java与Python的RPC调用)

时间:2021-11-05 06:50:34

上节我们介绍了基于Thrift实现java与java的RPC调用,本节我们基于Thrift实现Java与Python的RPC调用

首先,修改data.thirft文件,将命名空间由java改为py

namespace py thrift.generated

然后打开终端,输入命令 thrift --gen py src/thrift/data.thrift 生成Python代码

《精通并发与Netty》学习笔记(07 - 基于Thrift实现Java与Python的RPC调用)

打开Pycharm,新建Pure Python项目,将在idea中生成的python文件拷贝至Pycharm中

《精通并发与Netty》学习笔记(07 - 基于Thrift实现Java与Python的RPC调用)

编写python客户端程序py_client.py

# -*- coding:utf-8 -*-
from py.generated import PersonService, ttypes __author__ = 'kpzhang' from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TCompactProtocol try:
tSocket = TSocket.TSocket("localhost", 8899)
tSocket.setTimeout(900) transport = TTransport.TFramedTransport(tSocket)
protocol = TCompactProtocol.TCompactProtocol(transport)
client = PersonService.Client(protocol) transport.open() person = client.getPersonByUsername("张三") print(person.username)
print(person.age)
print(person.married) print('---------------------') newPerson = ttypes.Person();
newPerson.username = "李四"
newPerson.age = 30
newPerson.married = True client.savePerson(newPerson) transport.close() except Thrift.TException as tx:
print('%s' % tx.message)

分别启动java服务端和Python客户端,查看演示效果,(java端效果和上节效果一样,这里不再截图)

《精通并发与Netty》学习笔记(07 - 基于Thrift实现Java与Python的RPC调用)

本节我们介绍了基于Thrift实现Java与Python的RPC调用,下节我们结合netty4+springboot来做一个小项目