Thrift入门及Java实例演示

时间:2020-11-30 21:02:59

目录:

  • 概述
  • 下载配置
  • 基本概念
    1. 数据类型
    2. 服务端编码基本步骤
    3. 客户端编码基本步骤
    4. 数据传输协议
  • 实例演示(java)
    1.  thrift生成代码
    2.  实现接口Iface
    3. TSimpleServer服务模型
    4. TThreadPoolServer 服务模型
    5. TNonblockingServer 服务模型
    6. THsHaServer服务模型
    7. 异步客户端

[一]、概述

Thrift是一个软件框架,用来进行可扩展且跨语言的服务的开发。它结合了功能强大的软件堆栈和代码生成引擎,以构建在 C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, and OCaml 等等编程语言间无缝结合的、高效的服务。

Thrift最初由facebook开发,07年四月开放源码,08年5月进入apache孵化器。thrift允许你定义一个简单的定义文件中的数据类型和服务接口。以作为输入文件,编译器生成代码用来方便地生成RPC客户端和服务器通信的无缝跨编程语言。

官网地址:thrift.apache.org

推荐值得一看的文章:

[二]、下载配置

到官网下载最新版本,截止今日(2012-06-11)最新版本为0.8.0.

1. 如果是Maven构建项目的,直接在pom.xml 中添加如下内容:

12345 <dependency>  <groupId>org.apache.thrift</groupId>  <artifactId>libthrift</artifactId>  <version>0.8.0</version></dependency>

2.如果自己编译lib包,把下载的压缩包解压到X:盘,然后在X:\thrift-0.8.0\lib\java 目录下运行ant进行自动编译,会在X:\thrift-0.8.0\lib\java\build\ 目录下看到编译好的lib包:libthrift-0.8.0.jar

[三]、基本概念

1.数据类型

  • 基本类型:
    • bool:布尔值,true 或 false,对应 Java 的 boolean
    • byte:8 位有符号整数,对应 Java 的 byte
    • i16:16 位有符号整数,对应 Java 的 short
    • i32:32 位有符号整数,对应 Java 的 int
    • i64:64 位有符号整数,对应 Java 的 long
    • double:64 位浮点数,对应 Java 的 double
    • string:utf-8编码的字符串,对应 Java 的 String
  • 结构体类型:
    • struct:定义公共的对象,类似于 C 语言中的结构体定义,在 Java 中是一个 JavaBean
  • 容器类型:
    • list:对应 Java 的 ArrayList
    • set:对应 Java 的 HashSet
    • map:对应 Java 的 HashMap
  • 异常类型:
    • exception:对应 Java 的 Exception
  • 服务类型:
    • service:对应服务的类

2.服务端编码基本步骤:

  • 实现服务处理接口impl
  • 创建TProcessor
  • 创建TServerTransport
  • 创建TProtocol
  • 创建TServer
  • 启动Server

3.客户端编码基本步骤:

  • 创建Transport
  • 创建TProtocol
  • 基于TTransport和TProtocol创建 Client
  • 调用Client的相应方法

4.数据传输协议

  • TBinaryProtocol : 二进制格式.
  • TCompactProtocol : 压缩格式
  • TJSONProtocol : JSON格式
  • TSimpleJSONProtocol : 提供JSON只写协议, 生成的文件很容易通过脚本语言解析

tips:客户端和服务端的协议要一致

[四]、实例演示

1. thrift生成代码

创建Thrift文件:d:\demoHello.thrift ,内容如下:

12345 namespacejavacom.micmiu.thrift.demo service  HelloWorldService{  stringsayHello(1:stringusername)}

目录结构如下:



d:\demoHello.thriftd:\thrift-0.8.0.exe

thrift-0.8.0.exe 是官网提供的windows下编译工具,运用这个工具生成相关代码:

1 thrift-0.8.0.exe-r-genjava./demoHello.thrift

生成后的目录结构如下:

67891011121314
D:  demoHello.thrift    thrift-0.8.0.exe└─gen-java    └─com        └─micmiu            └─thrift                └─demo                        HelloWorldService.java

将生成的HelloWorldService.java 文件copy到自己测试的工程中,我的工程是用maven构建的,故在pom.xml中增加如下内容:

XHTML
12345678910 <dependency><groupId>org.apache.thrift</groupId><artifactId>libthrift</artifactId><version>0.8.0</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.5.8</version></dependency>

2. 实现接口Iface

java代码:HelloWorldImpl.java

123456789101112131415161718192021 packagecom.micmiu.thrift.demo; importorg.apache.thrift.TException; /*** blog http://www.micmiu.com** @author Michael**/publicclassHelloWorldImplimplementsHelloWorldService.Iface{ publicHelloWorldImpl(){} @OverridepublicStringsayHello(Stringusername)throwsTException{return"Hi,"+username+" welcome to my blog www.micmiu.com";} }

3.TSimpleServer服务端

简单的单线程服务模型,一般用于测试。

编写服务端server代码:HelloServerDemo.java

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 packagecom.micmiu.thrift.demo; importorg.apache.thrift.TProcessor;import org.apache.thrift.protocol.TBinaryProtocol;importorg.apache.thrift.protocol.TCompactProtocol;import org.apache.thrift.protocol.TJSONProtocol;importorg.apache.thrift.protocol.TSimpleJSONProtocol;import org.apache.thrift.server.TServer;importorg.apache.thrift.server.TSimpleServer;import org.apache.thrift.transport.TServerSocket; /*** blog http://www.micmiu.com** @author Michael**/public classHelloServerDemo{publicstaticfinalintSERVER_PORT=8090; publicvoidstartServer(){try{System.out.println("HelloWorld TSimpleServer start ...."); TProcessortprocessor=newHelloWorldService.Processor&lt;HelloWorldService.Iface&gt;(newHelloWorldImpl());// HelloWorldService.Processor&lt;HelloWorldService.Iface&gt; tprocessor =// new HelloWorldService.Processor&lt;HelloWorldService.Iface&gt;(// new HelloWorldImpl()); // 简单的单线程服务模型,一般用于测试TServerSocket serverTransport=newTServerSocket(SERVER_PORT);TServer.ArgstArgs=newTServer.Args(serverTransport);tArgs.processor(tprocessor);tArgs.protocolFactory(newTBinaryProtocol.Factory());// tArgs.protocolFactory(new TCompactProtocol.Factory());// tArgs.protocolFactory(new TJSONProtocol.Factory());TServer server=newTSimpleServer(tArgs);server.serve(); }catch(Exceptione){System.out.println("Server start error!!!");e.printStackTrace();}} /*** @param args*/publicstaticvoidmain(String[]args){HelloServerDemoserver=newHelloServerDemo();server.startServer();} }

编写客户端Client代码:HelloClientDemo.java

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 packagecom.micmiu.thrift.demo; importorg.apache.thrift.TException;import org.apache.thrift.protocol.TBinaryProtocol;importorg.apache.thrift.protocol.TCompactProtocol;import org.apache.thrift.protocol.TJSONProtocol;importorg.apache.thrift.protocol.TProtocol;import org.apache.thrift.transport.TSocket;importorg.apache.thrift.transport.TTransport;import org.apache.thrift.transport.TTransportException; /*** blog http://www.micmiu.com** @author Michael**/public classHelloClientDemo{ publicstaticfinalStringSERVER_IP="localhost";publicstaticfinalintSERVER_PORT=8090;publicstaticfinalintTIMEOUT=30000; /**** @param userName*/publicvoidstartClient(StringuserName){TTransporttransport=null;try{transport=newTSocket(SERVER_IP,SERVER_PORT,TIMEOUT);// 协议要和服务端一致TProtocolprotocol=newTBinaryProtocol(transport);// TProtocol protocol = new TCompactProtocol(transport);// TProtocol protocol = new TJSONProtocol(transport);HelloWorldService.Clientclient=newHelloWorldService.Client(protocol);transport.open();Stringresult=client.sayHello(userName);System.out.println("Thrify client result =: " +result);}catch(TTransportExceptione){e.printStackTrace();}catch(TExceptione){e.printStackTrace();}finally{if(null!=transport){transport.close();}}} /*** @param args*/publicstaticvoidmain(String[]args){HelloClientDemo client=newHelloClientDemo();client.startClient("Michael"); } }

先运行服务端程序,日志如下:

1 HelloWorldTSimpleServerstart....

再运行客户端调用程序,日志如下:

1 Thrifyclientresult=:Hi,Michaelwelcometomyblogwww.micmiu.com

测试成功,和预期的返回信息一致。

4.TThreadPoolServer 服务模型

线程池服务模型,使用标准的阻塞式IO,预先创建一组线程处理请求。

编写服务端代码:HelloServerDemo.java

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 packagecom.micmiu.thrift.demo; importorg.apache.thrift.TProcessor;import org.apache.thrift.protocol.TBinaryProtocol;importorg.apache.thrift.server.TServer;import org.apache.thrift.server.TThreadPoolServer;importorg.apache.thrift.transport.TServerSocket; /*** blog http://www.micmiu.com** @author Michael**/publicclassHelloServerDemo{publicstaticfinalintSERVER_PORT=8090; publicvoidstartServer(){try{System.out.println("HelloWorld TThreadPoolServer start ...."); TProcessor tprocessor=newHelloWorldService.Processor&lt;HelloWorldService.Iface&gt;(newHelloWorldImpl()); TServerSocketserverTransport=newTServerSocket(SERVER_PORT);TThreadPoolServer.ArgsttpsArgs=newTThreadPoolServer.Args(serverTransport);ttpsArgs.processor(tprocessor);ttpsArgs.protocolFactory(newTBinaryProtocol.Factory()); // 线程池服务模型,使用标准的阻塞式IO,预先创建一组线程处理请求。TServer server=newTThreadPoolServer(ttpsArgs);server.serve(); }catch(Exceptione){System.out.println("Server start error!!!");e.printStackTrace();}} /*** @param args*/publicstaticvoidmain(String[]args){HelloServerDemoserver=newHelloServerDemo();server.startServer();} }

客户端Client代码和之前的一样,只要数据传输的协议一致即可,客户端测试成功,结果如下:

1 Thrifyclientresult=:Hi,Michaelwelcometomyblogwww.micmiu.com

5.TNonblockingServer 服务模型

使用非阻塞式IO,服务端和客户端需要指定 TFramedTransport 数据传输的方式。

编写服务端代码:HelloServerDemo.java

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 packagecom.micmiu.thrift.demo; importorg.apache.thrift.TProcessor;import org.apache.thrift.protocol.TCompactProtocol;importorg.apache.thrift.server.TNonblockingServer;import org.apache.thrift.server.TServer;importorg.apache.thrift.transport.TFramedTransport;import org.apache.thrift.transport.TNonblockingServerSocket; /*** blog http://www.micmiu.com** @author Michael**/public classHelloServerDemo{publicstaticfinalintSERVER_PORT=8090; publicvoidstartServer(){try{System.out.println("HelloWorld TNonblockingServer start ...."); TProcessortprocessor=newHelloWorldService.Processor&lt;HelloWorldService.Iface&gt;(newHelloWorldImpl()); TNonblockingServerSocket tnbSocketTransport =newTNonblockingServerSocket(SERVER_PORT);TNonblockingServer.ArgstnbArgs=newTNonblockingServer.Args(tnbSocketTransport);tnbArgs.processor(tprocessor);tnbArgs.transportFactory(newTFramedTransport.Factory());tnbArgs.protocolFactory(newTCompactProtocol.Factory()); // 使用非阻塞式IO,服务端和客户端需要指定TFramedTransport数据传输的方式TServerserver=newTNonblockingServer(tnbArgs);server.serve(); }catch(Exceptione){System.out.println("Server start error!!!");e.printStackTrace();}} /*** @param args*/publicstaticvoidmain(String[]args){HelloServerDemo server=newHelloServerDemo();server.startServer();} }

编写客户端代码:HelloClientDemo.java

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 packagecom.micmiu.thrift.demo; importorg.apache.thrift.TException;import org.apache.thrift.protocol.TCompactProtocol;importorg.apache.thrift.protocol.TProtocol;import org.apache.thrift.transport.TFramedTransport;importorg.apache.thrift.transport.TSocket;import org.apache.thrift.transport.TTransport;importorg.apache.thrift.transport.TTransportException; /*** blog http://www.micmiu.com** @author Michael**/publicclassHelloClientDemo{ publicstaticfinalStringSERVER_IP="localhost";publicstaticfinalintSERVER_PORT=8090;publicstaticfinalintTIMEOUT=30000; /**** @param userName*/publicvoidstartClient(StringuserName){TTransport transport=null;try{transport=newTFramedTransport(newTSocket(SERVER_IP,SERVER_PORT,TIMEOUT));// 协议要和服务端一致TProtocolprotocol=newTCompactProtocol(transport);HelloWorldService.Clientclient=newHelloWorldService.Client(protocol);transport.open();Stringresult=client.sayHello(userName);System.out.println("Thrify client result =: " +result);}catch(TTransportExceptione){e.printStackTrace();}catch(TExceptione){e.printStackTrace();}finally{if(null!=transport){transport.close();}}} /*** @param args*/publicstaticvoidmain(String[]args){HelloClientDemo client=newHelloClientDemo();client.startClient("Michael"); } }

客户端的测试成功,结果如下:

1 Thrifyclientresult=:Hi,Michaelwelcometomyblogwww.micmiu.com

6.THsHaServer服务模型

半同步半异步的服务端模型,需要指定为: TFramedTransport 数据传输的方式。

编写服务端代码:HelloServerDemo.java

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 packagecom.micmiu.thrift.demo; importorg.apache.thrift.TProcessor;import org.apache.thrift.protocol.TBinaryProtocol;importorg.apache.thrift.protocol.TCompactProtocol;import org.apache.thrift.server.THsHaServer;importorg.apache.thrift.server.TNonblockingServer;import org.apache.thrift.server.TServer;importorg.apache.thrift.server.TSimpleServer;import org.apache.thrift.server.TThreadPoolServer;importorg.apache.thrift.transport.TFramedTransport;import org.apache.thrift.transport.TNonblockingServerSocket;importorg.apache.thrift.transport.TServerSocket; /*** blog http://www.micmiu.com** @author Michael**/publicclassHelloServerDemo{publicstaticfinalintSERVER_PORT=8090; publicvoidstartServer(){try{System.out.println("HelloWorld THsHaServer start ...."); TProcessor tprocessor=newHelloWorldService.Processor&lt;HelloWorldService.Iface&gt;(newHelloWorldImpl()); TNonblockingServerSockettnbSocketTransport=newTNonblockingServerSocket(SERVER_PORT);THsHaServer.ArgsthhsArgs=newTHsHaServer.Args(tnbSocketTransport);thhsArgs.processor(tprocessor);thhsArgs.transportFactory(newTFramedTransport.Factory());thhsArgs.protocolFactory(newTBinaryProtocol.Factory()); //半同步半异步的服务模型TServerserver=newTHsHaServer(thhsArgs);server.serve(); }catch(Exceptione){System.out.println("Server start error!!!");e.printStackTrace();}} /*** @param args*/publicstaticvoidmain(String[]args){HelloServerDemo server=newHelloServerDemo();server.startServer();} }

客户端代码和上面 4 中的类似,只要注意传输协议一致以及指定传输方式为TFramedTransport

7.异步客户端

编写服务端代码:HelloServerDemo.java

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 packagecom.micmiu.thrift.demo; importorg.apache.thrift.TProcessor;import org.apache.thrift.protocol.TCompactProtocol;importorg.apache.thrift.server.TNonblockingServer;import org.apache.thrift.server.TServer;importorg.apache.thrift.transport.TFramedTransport;import org.apache.thrift.transport.TNonblockingServerSocket; /*** blog http://www.micmiu.com** @author Michael**/public classHelloServerDemo{publicstaticfinalintSERVER_PORT=8090; publicvoidstartServer(){try{System.out.println("HelloWorld TNonblockingServer start ...."); TProcessortprocessor=newHelloWorldService.Processor&lt;HelloWorldService.Iface&gt;(newHelloWorldImpl()); TNonblockingServerSocket tnbSocketTransport =newTNonblockingServerSocket(SERVER_PORT);TNonblockingServer.ArgstnbArgs=newTNonblockingServer.Args(tnbSocketTransport);tnbArgs.processor(tprocessor);tnbArgs.transportFactory(newTFramedTransport.Factory());tnbArgs.protocolFactory(newTCompactProtocol.Factory()); // 使用非阻塞式IO,服务端和客户端需要指定TFramedTransport数据传输的方式TServerserver=newTNonblockingServer(tnbArgs);server.serve(); }catch(Exceptione){System.out.println("Server start error!!!");e.printStackTrace();}} /*** @param args*/publicstaticvoidmain(String[]args){HelloServerDemo server=newHelloServerDemo();server.startServer();} }

编写客户端Client代码:HelloAsynClientDemo.java

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 packagecom.micmiu.thrift.demo; importjava.util.concurrent.CountDownLatch;import java.util.concurrent.TimeUnit; import org.apache.thrift.TException;importorg.apache.thrift.async.AsyncMethodCallback;import org.apache.thrift.async.TAsyncClientManager;importorg.apache.thrift.protocol.TCompactProtocol;import org.apache.thrift.protocol.TProtocolFactory;importorg.apache.thrift.transport.TNonblockingSocket;import org.apache.thrift.transport.TNonblockingTransport; import com.micmiu.thrift.demo.HelloWorldService.AsyncClient.sayHello_call; /*** blog http://www.micmiu.com** @author Michael**/public classHelloAsynClientDemo{ publicstaticfinalStringSERVER_IP="localhost";publicstaticfinalintSERVER_PORT=8090;publicstaticfinalintTIMEOUT=30000; /**** @param userName*/publicvoidstartClient(StringuserName){try{TAsyncClientManager clientManager=newTAsyncClientManager();TNonblockingTransporttransport=newTNonblockingSocket(SERVER_IP,SERVER_PORT,TIMEOUT); TProtocolFactory tprotocol=newTCompactProtocol.Factory();HelloWorldService.AsyncClientasyncClient=newHelloWorldService.AsyncClient(tprotocol,clientManager,transport);System.out.println("Client start ....."); CountDownLatchlatch=newCountDownLatch(1);AsynCallback callBack=newAsynCallback(latch);System.out.println("call method sayHello start ...");asyncClient.sayHello(userName,callBack);System.out.println("call method sayHello .... end");booleanwait=latch.await(30,TimeUnit.SECONDS);System.out.println("latch.await =:" +wait);}catch(Exceptione){e.printStackTrace();}System.out.println("startClient end.");} publicclassAsynCallbackimplementsAsyncMethodCallback&lt;sayHello_call&gt;{privateCountDownLatchlatch; publicAsynCallback(CountDownLatchlatch){this.latch=latch;} @OverridepublicvoidonComplete(sayHello_callresponse){System.out.println("onComplete");try{// Thread.sleep(1000L * 1);System.out.println("AsynCall result =:"+response.getResult().toString());}catch(TExceptione){e.printStackTrace();}catch(Exceptione){e.printStackTrace();}finally{latch.countDown();}} @OverridepublicvoidonError(Exceptionexception){System.out.println("onError :" +exception.getMessage());latch.countDown();}} /*** @param args*/publicstaticvoidmain(String[]args){HelloAsynClientDemo client=newHelloAsynClientDemo();client.startClient("Michael"); } }

先运行服务程序,再运行客户端程序,测试结果如下:

1234567 Clientstart.....call method sayHellostart...callmethodsayHello....endonCompleteAsynCallresult=:Hi,Michaelwelcometomyblogwww.micmiu.comlatch.await=:truestartClientend.

————

原创文章,转载请注明: 转载自micmiu – 软件开发+生活点滴[http://www.micmiu.com/ ]

本文链接地址: http://www.micmiu.com/soa/rpc/thrift-sample/