1.简述
本文主要介绍thrift多语言、跨语言的代码实例。Thrift对多语言的支持非常不错,定义一个thrift接口文件,
通过thrift IDL compiler(代码生成引擎)生成各个语言的代码,将各自语言的代码放入各自语言的工程中,
写好服务端和客户端程序,通信的问题即刻解决。
2.简单架构图
示例的thrift接口文件,test8.thrift:
service TestService { string test(1: i32 num,2: string name)}
3.编码步骤
服务端编码步骤
实现服务处理接口impl创建TProcessor创建TServerTransport创建TProtocol创建TServer启动Server
4.客户端编码步骤
创建Transport创建TProtocol基于TTransport和TProtocol创建 Client调用Client的相应方法
5.python code
python底层代码生成之后,需要加入到工程中去。请确保你的环境中有thrift模块,如果没有请下载安装。下载地址:https://pypi.python.org/pypi/thrift/0.9.3 。安装方法很简单,解压下载的包后,命令行进入到thrift-0.9.3的目录下,使用命令:python setup.py install 即可完成模块的安装。
下面是python工程的包结构:
# -*- coding:utf-8 -*- from thrift.transport import TSocketfrom thrift.transport import TTransportfrom thrift.protocol import TBinaryProtocolfrom 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()
6.java编码
将生成的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(); } }}
7.demo运行
先运行python的服务端,如果运行正常,将打印出:python server:ready to start
再运行java的客户端,如果运行正常,将打印出:java client:test123