前面已经实现了纯java的thrift的实现。
现在实现实现一下python作为客户端和服务端的thrift的调用
1.python作为客户端,java作为服务端
java服务端代码参考前面写的博客
客户端python的准备:
1.使用mac下的PyCharm,专业的python开发工具
2.生成python代码
thrift --gen py thrift/data.thrift
3.在mac下安装thrift的python依赖
sudo python setup.py install 安装thrift的python依赖
4.查看安装依赖的路径
安装的路径:/Library/Python/2.7/site-packages
python客户端代码 :
# -*- coding:utf-8 -*- __author__ = ‘作者‘ //导入thrift生成的业务代码 from py.com.fubin.netty import PersonService from py.com.fubin.netty import ttypes //导入thrift框架的代码 from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TCompactProtocol //解决中文乱码问题 import sys reload(sys) sys.setdefaultencoding(‘utf-8 ‘) try: tSocket = TSocket.TSocket("localhost",8899) tSocket.setTimeout(600) transport = TTransport.TFramedTransport(tSocket) protocol = TCompactProtocol.TCompactProtocol(transport) client = PersonService.Client(protocol) transport.open() person = client.getPersonByUsername("zhangsan") print person.username print person.age print person.married print ‘=======================‘ newPerson = ttypes.Person() newPerson.username = "付彬" newPerson.age = 11 newPerson.married = True client.savePerson(newPerson) transport.close() except Thrift.TException , tx: print ‘%s‘ % tx.message
中文乱码问题:导入系统库
import sys reload(sys) sys.setdefaultencoding(‘utf-8 ‘)
python作为服务端
1.编写业务接口类
# -*- coding:utf-8 -*- __author__ = ‘作者‘ from py.com.fubin.netty import ttypes class PersonServiceImpl : def getPersonByUsername(self,username): print "got client param :" +username person = ttypes.Person() person.username = username person.age = 112 person.married = True return person def savePerson(self ,person): print "got client param : " print person.username print person.age print person.married
编写服务端初始化类:
# -*- coding:utf-8 -*- __author__ = ‘作者‘ from py.com.fubin.netty import PersonService from PythonServiceImpl import PersonServiceImpl from py.com.fubin.netty import ttypes from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TCompactProtocol from thrift.server import TServer import sys reload(sys) sys.setdefaultencoding(‘utf-8 ‘) try: personServiceHandler = PersonServiceImpl() processor = PersonService.Processor(personServiceHandler) serverSocket = TSocket.TServerSocket(port=8899) transportFactory = TTransport.TFramedTransportFactory() protocolFactory = TCompactProtocol.TCompactProtocolFactory() server = TServer.TSimpleServer(processor,serverSocket,transportFactory,protocolFactory) server.serve() except Thrift.TException , tx: print ‘%s‘ % tx.message
到这里,一个简单的python实现的thrift调用例子就完成了。
不积跬步,无以至千里,每天进步一点点。
时间: 2024-10-26 09:37:34