Thrift 的学习笔记

    最近做的项目是使用CXF编写Service,给公司的其他项目提供接口的。由于需求问题,改用Thrift。下面就总结下自己学习Apache Thrift的内容,和例子。

1. 下载thrift-0.9.0.exe 。我使用的是win7系统,将该文件复制到C盘Windows下,并改名thrift.exe方便执行命令。运行cmd.exe。输入命令

thrift -version

 输出Thrift version 0.9.0则可以使用该命令。

2.编写HelloWorld.thrift(D:\)。

namespace java com.test.rpc

service TestService {

      string getUsername(1:i32 id);
 
}

在之前打开的cmd.exe中,切换路径到存放thrift文件的文件夹下,执行命令:

D:

thrift --gen java HelloWorld.thrift
 

没有报错的话,在D盘下会生成一个文件夹gen-java ,刚刚执行命令生成的文件com\test\rpc\TestService.java

TestService.java是编译好的客户端和服务端的支持代码。

3.新建一个工程,将com文件夹直接考到工程的src下。或者可以将文件添加到已有的项目中。

工程导入Thrift相关的jar包。简单的编写服务和客户端。

libthrift.jar
log4j-1.2.16.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.6.1.jar

4.编写接口的实现类

public class ThriftServer implement TestService.Iface{

      public String getUsername(int id){
               if(id>0){
                      return "Hello Join!";
               } else {
                      return "not exist!";
               }
      }

       public static void main(String[] args){
              try{
                    ThriftServer t = new ThriftServer();

                    TestService.Processor p = new TestService.Processor(t);

                    TServerTransport serverTransport = new TServerTransport(9090);

                    TServer server = new TThreadPoolServer(p, serverTransport);

                    System.out.println("Starting the server ...");
 
                    server.serve();

             }catch (Exception e){
                    e.printStackTrace();
             }
      }
 } 

5.编写客户端代码

public class ThriftClient{

       public static void main(String[] args){

               TTransport transport = new TSocket("localhost", 9090);
              
               TProtocol protocol = new TBinaryProtocol(transport);

               TestService.Client cient = new TestService.Client(protocol);

               try{
                       transport.open();
                       String str = client.getUsername(10);
                       System.out.println(str);

               } catch(TException e){
                       e.printStackTrace();
               } finally {
                       transport.close();
               }

       }
}
 

6.执行ThriftServer文件,启动服务

7.执行ThriftClient文件,测试

猜你喜欢

转载自sleepingxu.iteye.com/blog/1743920
今日推荐