标签:
1.简述
本文主要介绍thrift多语言、跨语言的代码实例。Thrift对多语言的支持非常不错,定义一个thrift接口文件,通过thrift IDL compiler(代码生成引擎)生成各个语言的代码,将各自语言的代码放入各自语言的工程中,写好服务端和客户端程序,通信的问题即刻解决。
2.简单架构图
示例的thrift接口文件,test8.thrift:
service TestService { string test(1: i32 num,2: string name) }代码生成方法,文件定义方法,请参见thrift系列文章:
快速入门:http://blog.csdn.net/hrn1216/article/details/51274934
类型定义:http://blog.csdn.net/hrn1216/article/details/51306395
3.python code
python底层代码生成之后,需要加入到工程中去。请确保你的环境中有thrift模块,如果没有请下载安装。下载地址:https://pypi.python.org/pypi/thrift/0.9.3 。安装方法很简单,解压下载的包后,命令行进入到thrift-0.9.3的目录下,使用命令:python setup.py install 即可完成模块的安装。
下面是python工程的包结构:
以下是 python 服务端的代码:
# -*- coding:utf-8 -*- from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from thrift.server import TServer #根据实际的包结构去引入 from test8 import TestService #test8.thrift的具体实现 class TestServiceHandler: def __init__(self): self.log = {} def test(self,num,name): return name + str(num) if __name__ == '__main__': handler = TestServiceHandler() processor = TestService.Processor(handler) transport = TSocket.TServerSocket(host='127.0.0.1',port=9090) tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) print 'python server:ready to start' server.serve()
将生成的TestService.java加入到java工程中去,以下是java客户端的代码:
package test8; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; public class Client { public static void main(String[] args) { //配置服务端的请求信息 TTransport transport = new TSocket("127.0.0.1", 9090); try { transport.open(); TProtocol protocol = new TBinaryProtocol(transport); TestService.Client client = new TestService.Client(protocol); //接口调用 String rs = client.test(123, "test"); //打印调用结果 System.out.println("java client:" + rs); transport.close(); } catch (TTransportException e) { e.printStackTrace(); } catch (TException e) { e.printStackTrace(); } } }
先运行python的服务端,如果运行正常,将打印出:python server:ready to start
再运行java的客户端,如果运行正常,将打印出:java client:test123
本文内容参考如下:
【1】http://thrift.apache.org/
注意:
如您发现本文档中有明显错误的地方,
或者您发现本文档中引用了他人的资料而未进行说明时,请联系我进行更正。
转载或使用本文档时,请作醒目说明。
必要时请联系作者,否则将追究相应的法律责任。
note:
If you find this document with any error ,
Or if you find any illegal citations , please contact me correct.
Reprint or use of this document,Please explain for striking.
Please contact the author if necessary, or they will pursue the corresponding legal responsibility.
thrift系列 - 多语言实例 for java和python
标签:
原文地址:http://blog.csdn.net/hrn1216/article/details/51363902