`
sleepingxu
  • 浏览: 11272 次
  • 性别: Icon_minigender_2
  • 来自: 广州
社区版块
存档分类
最新评论

Thrift0.9.0的简单示例,java实现客户端服务端

阅读更多

前提,安装了Thrift-0.9.0,用到的jar包:

libthrift-0.9.0.jar
log4j.1.2.14.jar
slf4j-api-1.5.8.jar
slf4j-log4j12-1.5.8.jar

 

编写test.thrift文件

namespace java com.test

struct RS {
   1:i32 code=0;
   2:string id;
   3:list<RRL>  children;
   4:string account
}

struct RRL {
   1:string id;
   2:string name;
   2:string desc
}

service CWS {
   RS getUserInfo(1:string name)
}

 

执行以下命令

cd d:
thrift --gen java test.thrift

 

新建java工程,吧D盘下gen-java下的com文件复制到项目的src下,导入jar包。文件会报错。只要把报错的地方的@override删除即可。

 

编写接口实现代码和服务端代码:

public class CWSImpl implements CWS.Iface{
    public RS getUserInfo(String name) throws TException{
           if(name==null || name.equals("")){
                  return null;
           }
           RS rs = new RS();
           rs.setCode(0);
           rs.setId("1001");
    }

     public static void main(String[] args){
          try{
               CWSImpl handler = new CWSImpl();
               
               CWS.Processor<CWSImpl> processor =  new CWS.Processor<CWSImpl>(handler);
               
               TServerTransport serverTransport = new TServerSocket(9000);
              
               TServer server = new TSimpleServer(new TServer.Args(
                                     serverTransport).processor(processor));
               
               System.out.println("Starting server...");
               server.serve();
          
          } catch(Exception e){
               e.printStackTrace();
          }
     }
}
 

编写客户端代码:

public class TestClient{

      public static void main(String[] args){

            try{
               TTransport transport = new TSocket("localhost", 9000);
               transport.open();

               TProtocol protocol = new TBinaryProtocol(transport);

               CWS.Client client = new CWS.Client(protocol);

               System.out.println("client test: ");
               RS rs = client.getUserInfo("tom");
               System.out.println("code: " + rs.getCode() + ", id: " + rs.getId());

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

运行

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics