RPC之Thrift 介绍及java实例

Thrift 介绍及java实例

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
推荐值得一看的文章:
http://jnb.ociweb.com/jnb/jnbJun2009.html
http://wiki.apache.org/thrift

http://thrift.apache.org/static/files/thrift-20070401.pdf

 

  • Thrift 基础架构

Thrift是一个服务端和客户端的架构体系,就是socket传输,Thrift 具有自己内部定义的传输协议规范(TProtocol)和传输数据标准(TTransports),通过IDL脚本对传输数据的数据结构(struct) 和传输数据的业务逻辑(service)根据不同的运行环境快速的构建相应的代码,并且通过自己内部的序列化机制对传输的数据进行简化和压缩提高高并发、 大型系统中数据交互的成本,下图描绘了Thrift的整体架构,分为6个部分:

1.你的业务逻辑实现(You Code) 

2.客户端和服务端对应的Service 

3.执行读写操作的计算结果

4.TProtocol 

5.TTransports  

6.底层I/O通信

 

  • Thrift 软件栈
  Thrift对软件栈的定义非常的清晰, 使得各个组件能够松散的耦合, 针对不同的应用场景, 选择不同是方式去搭建服务. 

 

评注:
  Transport: 传输层,定义数据传输方式,可以为TCP/IP传输,内存共享或者文件共享等
  protocol: 协议层, 定义数据传输格式,可以为二进制或者XML等
  Processor: 处理层, 这部分由定义的idl来生成, 封装了协议输入输出流, 并委托给用户实现的handler进行处理.
  Server: 服务层, 整合上述组件, 提供网络模型(单线程/多线程/事件驱动), 最终形成真正的服务.

  • Thrift脚本的数据类型
 * Base Types:基本类型
bool        Boolean, one byte
byte        Signed byte
i16         Signed 16-bit integer
i32         Signed 32-bit integer
i64         Signed 64-bit integer
double      64-bit floating point value
string      String
binary      Blob (byte array)

 * Struct:结构体类型
 * Container:容器类型,即List、Set、Map
map<t1,t2> Map from one type to another
list<t1>    Ordered list of one type
set<t1>     Set of unique elements of one type
 * Exception:异常类型
 * Service: 定义对象的接口,和一系列方法
  • 协议
  Thrift可以让你选择客户端与服务端之间传输通信协议的类别,在传输协议上总体上划分为文本(text)和二进制(binary)传输协议, 为节约带宽,提供传输效率,一般情况下使用二进制类型的传输协议为多数,但有时会还是会使用基于文本类型的协议,这需要根据项目/产品中的实际需求:
    * TBinaryProtocol – 二进制编码格式进行数据传输。
    * TCompactProtocol – 这种协议非常有效的,使用Variable-Length Quantity (VLQ) 编码对数据进行压缩。
    * TJSONProtocol – 使用JSON的数据编码协议进行数据传输。
    * TSimpleJSONProtocol – 这种节约只提供JSON只写的协议,适用于通过脚本语言解析
    * TDebugProtocol – 在开发的过程中帮助开发人员调试用的,以文本的形式展现方便阅读。
  • 传输层
    * TSocket- 使用堵塞式I/O进行传输,也是最常见的模式。
    * TFramedTransport- 使用非阻塞方式,按块的大小,进行传输,类似于Java中的NIO。
    * TFileTransport- 顾名思义按照文件的方式进程传输,虽然这种方式不提供Java的实现,但是实现起来非常简单。
    * TMemoryTransport- 使用内存I/O,就好比Java中的ByteArrayOutputStream实现。

    * TZlibTransport- 使用执行zlib压缩,不提供Java的实现。

  • Thrift 高性能网络服务模型
1). TServer类层次体系


TSimpleServer/TThreadPoolServer是阻塞服务模型
TNonblockingServer/THsHaServer/TThreadedSelectotServer是非阻塞服务模型(NIO)
2). TServer抽象类的定义
内部静态类Args的定义, 用于TServer类用于串联软件栈(传输层, 协议层, 处理层)
  1.  
    public abstract class TServer {
  2.  
      public static class Args extends AbstractServerArgs<Args> {
  3.  
        public Args(TServerTransport transport) {
  4.  
          super(transport);
  5.  
        }
  6.  
      }
  7.  
     
  8.  
      public static abstract class AbstractServerArgs<T extends AbstractServerArgs<T>> {
  9.  
        public AbstractServerArgs(TServerTransport transport);
  10.  
        public T processorFactory(TProcessorFactory factory);
  11.  
        public T processor(TProcessor processor);
  12.  
        public T transportFactory(TTransportFactory factory);
  13.  
        public T protocolFactory(TProtocolFactory factory);
  14.  
      }
  15.  
    }
TServer类定义的抽象类
  1.  
    public abstract class TServer {
  2.  
      public abstract void serve();
  3.  
      public void stop();
  4.  
     
  5.  
      public boolean isServing();
  6.  
      public void setServerEventHandler(TServerEventHandler eventHandler);
  7.  
    }
评注:抽象函数serve由具体的TServer实例来实现, 而并非所有的服务都需要优雅的退出, 因此stop没有被定义为抽象。

各种服务模型介绍如下:

    * TSimpleServer -  单线程服务器端使用标准的堵塞式I/O,只适合测试开发使用。抽象代码描述如下:

  1.  
    // *) server socket进行监听
  2.  
    serverSocket.listen();
  3.  
    while ( isServing() ) {
  4.  
      // *) 接受socket链接
  5.  
      client = serverSocket.accept();
  6.  
      // *) 封装处理器
  7.  
      processor = factory.getProcess(client);
  8.  
      while ( true ) {
  9.  
        // *) 阻塞处理rpc的输入/输出
  10.  
        if ( !processor.process(input, output) ) {
  11.  
          break;
  12.  
        }
  13.  
      }
  14.  
    }

 

    * TThreadPoolServer -  多线程服务器端使用标准的堵塞式I/O。引入了线程池,实现的模型是One Thread Per Connection。

线程池代码片段如下:

  1.  
    private static ExecutorService createDefaultExecutorService(Args args) {
  2.  
    SynchronousQueue<Runnable> executorQueue =
  3.  
    new SynchronousQueue<Runnable>();
  4.  
    return new ThreadPoolExecutor(args.minWorkerThreads,
  5.  
    args.maxWorkerThreads,
  6.  
    60,
  7.  
    TimeUnit.SECONDS,
  8.  
    executorQueue);
  9.  
    }

采用同步队列(SynchronousQueue), 线程池采用能线程数可伸缩的模式. 

主线程循环:

  1.  
    setServing(true);
  2.  
    while (!stopped_) {
  3.  
      try {
  4.  
        TTransport client = serverTransport_.accept();
  5.  
        WorkerProcess wp = new WorkerProcess(client);
  6.  
        executorService_.execute(wp);
  7.  
      } catch (TTransportException ttx) {
  8.  
      }
  9.  
    }
   拆分了监听线程(accept)和处理客户端连接的工作线程(worker), 监听线程每接到一个客户端, 就投给线程池去处理. 这种模型能提高并发度, 但并发数取决于线程数, IO依旧阻塞, 从而限制该服务的服务能力。

   * TNonblockingServer – 采用NIO的模式, 借助Channel/Selector机制, 采用IO事件模型来处理。

 

  1.  
    private void select() {
  2.  
      try {
  3.  
        selector.select(); // wait for io events.
  4.  
        // process the io events we received
  5.  
        Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
  6.  
        while (!stopped_ && selectedKeys.hasNext()) {
  7.  
          SelectionKey key = selectedKeys.next();
  8.  
          selectedKeys.remove();
  9.  
          if (key.isAcceptable()) {
  10.  
            handleAccept(); // deal with accept
  11.  
          } else if (key.isReadable()) {
  12.  
            handleRead(key); // deal with reads
  13.  
          } else if (key.isWritable()) {
  14.  
            handleWrite(key); // deal with writes
  15.  
          }
  16.  
        }
  17.  
      } catch (IOException e) {
  18.  
      }
  19.  
    }
select代码里对accept/read/write等IO事件进行监控和处理, 唯一可惜的这个单线程处理. 当遇到handler里有阻塞的操作时, 会导致整个服务被阻塞住。
   *THsHaServer - 半同步半异步    

鉴于TNonblockingServer的缺点, THsHa引入了线程池去处理, 其模型把读写任务放到线程池去处理。HsHa是: Half-sync/Half-async的处理模式, Half-aysnc是在处理IO事件上(accept/read/write io), Half-sync用于handler对rpc的同步处理上.

   *TThreadedSelectorServer- 多线程服务器端使用非堵塞式I/O,是对以上NonblockingServer的扩充, 其分离了Accept和Read/Write的Selector线程, 同时引入Worker工作线程池. 它也是种Half-sync/Half-async的服务模型,也是最成熟,也是被业界所推崇的RPC服务模型。

 

MainReactor就是Accept线程, 用于监听客户端连接, SubReactor采用IO事件线程(多个), 主要负责对所有客户端的IO读写事件进行处理. 而Worker工作线程主要用于处理每个rpc请求的handler回调处理(这部分是同步的)。

  • Java简单实例
1.定义接口描述
创建Thrift文件HelloWorld.thrift,定义接口描述:
 namespace java cn.slimsmart.thrift.demo.helloworld
 service HelloWorld{ 
  string sayHello(1:string username)
 } 
2.生成java接口文件
使用thrift.exe工具生成java接口文件,下载thrift-0.9.2.exe工具
thrift-0.9.2.exe -r -gen java ./HelloWorld.thrift
  1.  
    /**
  2.  
    * Autogenerated by Thrift Compiler (0.9.2)
  3.  
    *
  4.  
    * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
  5.  
    * @generated
  6.  
    */
  7.  
    package cn.slimsmart.thrift.demo.helloworld;
  8.  
     
  9.  
    import java.util.ArrayList;
  10.  
    import java.util.BitSet;
  11.  
    import java.util.Collections;
  12.  
    import java.util.EnumMap;
  13.  
    import java.util.EnumSet;
  14.  
    import java.util.HashMap;
  15.  
    import java.util.List;
  16.  
    import java.util.Map;
  17.  
     
  18.  
    import javax.annotation.Generated;
  19.  
     
  20.  
    import org.apache.thrift.TException;
  21.  
    import org.apache.thrift.async.AsyncMethodCallback;
  22.  
    import org.apache.thrift.protocol.TTupleProtocol;
  23.  
    import org.apache.thrift.scheme.IScheme;
  24.  
    import org.apache.thrift.scheme.SchemeFactory;
  25.  
    import org.apache.thrift.scheme.StandardScheme;
  26.  
    import org.apache.thrift.scheme.TupleScheme;
  27.  
    import org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer;
  28.  
    import org.slf4j.Logger;
  29.  
    import org.slf4j.LoggerFactory;
  30.  
     
  31.  
    /**
  32.  
    * 通过HelloWord.thrift 生成的接口类
  33.  
    */
  34.  
    @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
  35.  
    @Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2015-2-28")
  36.  
    public class HelloWorld {
  37.  
     
  38.  
    //同步接口
  39.  
    public interface Iface {
  40.  
    public String sayHello(String username) throws org.apache.thrift.TException;
  41.  
    }
  42.  
     
  43.  
    //异步接口
  44.  
    public interface AsyncIface {
  45.  
    public void sayHello(String username, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;
  46.  
    }
  47.  
     
  48.  
    //客户端同步接口实现代理类
  49.  
    public static class Client extends org.apache.thrift.TServiceClient implements Iface {
  50.  
    public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {
  51.  
    public Factory() {}
  52.  
    public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
  53.  
    return new Client(prot);
  54.  
    }
  55.  
    public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
  56.  
    return new Client(iprot, oprot);
  57.  
    }
  58.  
    }
  59.  
     
  60.  
    public Client(org.apache.thrift.protocol.TProtocol prot)
  61.  
    {
  62.  
    super(prot, prot);
  63.  
    }
  64.  
     
  65.  
    public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
  66.  
    super(iprot, oprot);
  67.  
    }
  68.  
     
  69.  
    public String sayHello(String username) throws org.apache.thrift.TException
  70.  
    {
  71.  
    send_sayHello(username);
  72.  
    return recv_sayHello();
  73.  
    }
  74.  
     
  75.  
    public void send_sayHello(String username) throws org.apache.thrift.TException
  76.  
    {
  77.  
    sayHello_args args = new sayHello_args();
  78.  
    args.setUsername(username);
  79.  
    sendBase("sayHello", args);
  80.  
    }
  81.  
     
  82.  
    public String recv_sayHello() throws org.apache.thrift.TException
  83.  
    {
  84.  
    sayHello_result result = new sayHello_result();
  85.  
    receiveBase(result, "sayHello");
  86.  
    if (result.isSetSuccess()) {
  87.  
    return result.success;
  88.  
    }
  89.  
    throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "sayHello failed: unknown result");
  90.  
    }
  91.  
     
  92.  
    }
  93.  
     
  94.  
    //客户端异步接口实现代理类
  95.  
    public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {
  96.  
    public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {
  97.  
    private org.apache.thrift.async.TAsyncClientManager clientManager;
  98.  
    private org.apache.thrift.protocol.TProtocolFactory protocolFactory;
  99.  
    public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
  100.  
    this.clientManager = clientManager;
  101.  
    this.protocolFactory = protocolFactory;
  102.  
    }
  103.  
    public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {
  104.  
    return new AsyncClient(protocolFactory, clientManager, transport);
  105.  
    }
  106.  
    }
  107.  
     
  108.  
    public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {
  109.  
    super(protocolFactory, clientManager, transport);
  110.  
    }
  111.  
     
  112.  
    public void sayHello(String username, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {
  113.  
    checkReady();
  114.  
    sayHello_call method_call = new sayHello_call(username, resultHandler, this, ___protocolFactory, ___transport);
  115.  
    this.___currentMethod = method_call;
  116.  
    ___manager.call(method_call);
  117.  
    }
  118.  
     
  119.  
    public static class sayHello_call extends org.apache.thrift.async.TAsyncMethodCall {
  120.  
    private String username;
  121.  
    public sayHello_call(String username, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
  122.  
    super(client, protocolFactory, transport, resultHandler, false);
  123.  
    this.username = username;
  124.  
    }
  125.  
     
  126.  
    public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
  127.  
    prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("sayHello", org.apache.thrift.protocol.TMessageType.CALL, 0));
  128.  
    sayHello_args args = new sayHello_args();
  129.  
    args.setUsername(username);
  130.  
    args.write(prot);
  131.  
    prot.writeMessageEnd();
  132.  
    }
  133.  
     
  134.  
    public String getResult() throws org.apache.thrift.TException {
  135.  
    if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
  136.  
    throw new IllegalStateException("Method call not finished!");
  137.  
    }
  138.  
    org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
  139.  
    org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
  140.  
    return (new Client(prot)).recv_sayHello();
  141.  
    }
  142.  
    }
  143.  
     
  144.  
    }
  145.  
     
  146.  
    //服务端同步代理调用处理器
  147.  
    public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I> implements org.apache.thrift.TProcessor {
  148.  
    public Processor(I iface) {
  149.  
    super(iface, getProcessMap(new HashMap<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));
  150.  
    }
  151.  
     
  152.  
    protected Processor(I iface, Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
  153.  
    super(iface, getProcessMap(processMap));
  154.  
    }
  155.  
     
  156.  
    private static <I extends Iface> Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
  157.  
    processMap.put("sayHello", new sayHello());
  158.  
    return processMap;
  159.  
    }
  160.  
     
  161.  
    public static class sayHello<I extends Iface> extends org.apache.thrift.ProcessFunction<I, sayHello_args> {
  162.  
    public sayHello() {
  163.  
    super("sayHello");
  164.  
    }
  165.  
     
  166.  
    public sayHello_args getEmptyArgsInstance() {
  167.  
    return new sayHello_args();
  168.  
    }
  169.  
     
  170.  
    protected boolean isOneway() {
  171.  
    return false;
  172.  
    }
  173.  
     
  174.  
    public sayHello_result getResult(I iface, sayHello_args args) throws org.apache.thrift.TException {
  175.  
    sayHello_result result = new sayHello_result();
  176.  
    result.success = iface.sayHello(args.username);
  177.  
    return result;
  178.  
    }
  179.  
    }
  180.  
     
  181.  
    }
  182.  
     
  183.  
    //服务端异步代理调用处理器
  184.  
    public static class AsyncProcessor<I extends AsyncIface> extends org.apache.thrift.TBaseAsyncProcessor<I> {
  185.  
    private static final Logger LOGGER = LoggerFactory.getLogger(AsyncProcessor.class.getName());
  186.  
    public AsyncProcessor(I iface) {
  187.  
    super(iface, getProcessMap(new HashMap<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));
  188.  
    }
  189.  
     
  190.  
    protected AsyncProcessor(I iface, Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
  191.  
    super(iface, getProcessMap(processMap));
  192.  
    }
  193.  
     
  194.  
    private static <I extends AsyncIface> Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase,?>> getProcessMap(Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
  195.  
    processMap.put("sayHello", new sayHello());
  196.  
    return processMap;
  197.  
    }
  198.  
     
  199.  
    public static class sayHello<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, sayHello_args, String> {
  200.  
    public sayHello() {
  201.  
    super("sayHello");
  202.  
    }
  203.  
     
  204.  
    public sayHello_args getEmptyArgsInstance() {
  205.  
    return new sayHello_args();
  206.  
    }
  207.  
     
  208.  
    public AsyncMethodCallback<String> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {
  209.  
    final org.apache.thrift.AsyncProcessFunction fcall = this;
  210.  
    return new AsyncMethodCallback<String>() {
  211.  
    public void onComplete(String o) {
  212.  
    sayHello_result result = new sayHello_result();
  213.  
    result.success = o;
  214.  
    try {
  215.  
    fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
  216.  
    return;
  217.  
    } catch (Exception e) {
  218.  
    LOGGER.error("Exception writing to internal frame buffer", e);
  219.  
    }
  220.  
    fb.close();
  221.  
    }
  222.  
    public void onError(Exception e) {
  223.  
    byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
  224.  
    org.apache.thrift.TBase msg;
  225.  
    {
  226.  
    msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
  227.  
    msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
  228.  
    }
  229.  
    try {
  230.  
    fcall.sendResponse(fb,msg,msgType,seqid);
  231.  
    return;
  232.  
    } catch (Exception ex) {
  233.  
    LOGGER.error("Exception writing to internal frame buffer", ex);
  234.  
    }
  235.  
    fb.close();
  236.  
    }
  237.  
    };
  238.  
    }
  239.  
     
  240.  
    protected boolean isOneway() {
  241.  
    return false;
  242.  
    }
  243.  
     
  244.  
    public void start(I iface, sayHello_args args, org.apache.thrift.async.AsyncMethodCallback<String> resultHandler) throws TException {
  245.  
    iface.sayHello(args.username,resultHandler);
  246.  
    }
  247.  
    }
  248.  
     
  249.  
    }
  250.  
     
  251.  
    //参数
  252.  
    public static class sayHello_args implements org.apache.thrift.TBase<sayHello_args, sayHello_args._Fields>, java.io.Serializable, Cloneable, Comparable<sayHello_args> {
  253.  
    private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sayHello_args");
  254.  
     
  255.  
    private static final org.apache.thrift.protocol.TField USERNAME_FIELD_DESC = new org.apache.thrift.protocol.TField("username", org.apache.thrift.protocol.TType.STRING, (short)1);
  256.  
     
  257.  
    private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
  258.  
    static {
  259.  
    schemes.put(StandardScheme.class, new sayHello_argsStandardSchemeFactory());
  260.  
    schemes.put(TupleScheme.class, new sayHello_argsTupleSchemeFactory());
  261.  
    }
  262.  
     
  263.  
    public String username; // required
  264.  
     
  265.  
    /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  266.  
    public enum _Fields implements org.apache.thrift.TFieldIdEnum {
  267.  
    USERNAME((short)1, "username");
  268.  
     
  269.  
    private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
  270.  
     
  271.  
    static {
  272.  
    for (_Fields field : EnumSet.allOf(_Fields.class)) {
  273.  
    byName.put(field.getFieldName(), field);
  274.  
    }
  275.  
    }
  276.  
     
  277.  
    /**
  278.  
    * Find the _Fields constant that matches fieldId, or null if its not found.
  279.  
    */
  280.  
    public static _Fields findByThriftId(int fieldId) {
  281.  
    switch(fieldId) {
  282.  
    case 1: // USERNAME
  283.  
    return USERNAME;
  284.  
    default:
  285.  
    return null;
  286.  
    }
  287.  
    }
  288.  
     
  289.  
    /**
  290.  
    * Find the _Fields constant that matches fieldId, throwing an exception
  291.  
    * if it is not found.
  292.  
    */
  293.  
    public static _Fields findByThriftIdOrThrow(int fieldId) {
  294.  
    _Fields fields = findByThriftId(fieldId);
  295.  
    if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
  296.  
    return fields;
  297.  
    }
  298.  
     
  299.  
    /**
  300.  
    * Find the _Fields constant that matches name, or null if its not found.
  301.  
    */
  302.  
    public static _Fields findByName(String name) {
  303.  
    return byName.get(name);
  304.  
    }
  305.  
     
  306.  
    private final short _thriftId;
  307.  
    private final String _fieldName;
  308.  
     
  309.  
    _Fields(short thriftId, String fieldName) {
  310.  
    _thriftId = thriftId;
  311.  
    _fieldName = fieldName;
  312.  
    }
  313.  
     
  314.  
    public short getThriftFieldId() {
  315.  
    return _thriftId;
  316.  
    }
  317.  
     
  318.  
    public String getFieldName() {
  319.  
    return _fieldName;
  320.  
    }
  321.  
    }
  322.  
     
  323.  
    // isset id assignments
  324.  
    public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  325.  
    static {
  326.  
    Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
  327.  
    tmpMap.put(_Fields.USERNAME, new org.apache.thrift.meta_data.FieldMetaData("username", org.apache.thrift.TFieldRequirementType.DEFAULT,
  328.  
    new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
  329.  
    metaDataMap = Collections.unmodifiableMap(tmpMap);
  330.  
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sayHello_args.class, metaDataMap);
  331.  
    }
  332.  
     
  333.  
    public sayHello_args() {
  334.  
    }
  335.  
     
  336.  
    public sayHello_args(
  337.  
    String username)
  338.  
    {
  339.  
    this();
  340.  
    this.username = username;
  341.  
    }
  342.  
     
  343.  
    /**
  344.  
    * Performs a deep copy on <i>other</i>.
  345.  
    */
  346.  
    public sayHello_args(sayHello_args other) {
  347.  
    if (other.isSetUsername()) {
  348.  
    this.username = other.username;
  349.  
    }
  350.  
    }
  351.  
     
  352.  
    public sayHello_args deepCopy() {
  353.  
    return new sayHello_args(this);
  354.  
    }
  355.  
     
  356.  
    @Override
  357.  
    public void clear() {
  358.  
    this.username = null;
  359.  
    }
  360.  
     
  361.  
    public String getUsername() {
  362.  
    return this.username;
  363.  
    }
  364.  
     
  365.  
    public sayHello_args setUsername(String username) {
  366.  
    this.username = username;
  367.  
    return this;
  368.  
    }
  369.  
     
  370.  
    public void unsetUsername() {
  371.  
    this.username = null;
  372.  
    }
  373.  
     
  374.  
    /** Returns true if field username is set (has been assigned a value) and false otherwise */
  375.  
    public boolean isSetUsername() {
  376.  
    return this.username != null;
  377.  
    }
  378.  
     
  379.  
    public void setUsernameIsSet(boolean value) {
  380.  
    if (!value) {
  381.  
    this.username = null;
  382.  
    }
  383.  
    }
  384.  
     
  385.  
    public void setFieldValue(_Fields field, Object value) {
  386.  
    switch (field) {
  387.  
    case USERNAME:
  388.  
    if (value == null) {
  389.  
    unsetUsername();
  390.  
    } else {
  391.  
    setUsername((String)value);
  392.  
    }
  393.  
    break;
  394.  
     
  395.  
    }
  396.  
    }
  397.  
     
  398.  
    public Object getFieldValue(_Fields field) {
  399.  
    switch (field) {
  400.  
    case USERNAME:
  401.  
    return getUsername();
  402.  
     
  403.  
    }
  404.  
    throw new IllegalStateException();
  405.  
    }
  406.  
     
  407.  
    /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  408.  
    public boolean isSet(_Fields field) {
  409.  
    if (field == null) {
  410.  
    throw new IllegalArgumentException();
  411.  
    }
  412.  
     
  413.  
    switch (field) {
  414.  
    case USERNAME:
  415.  
    return isSetUsername();
  416.  
    }
  417.  
    throw new IllegalStateException();
  418.  
    }
  419.  
     
  420.  
    @Override
  421.  
    public boolean equals(Object that) {
  422.  
    if (that == null)
  423.  
    return false;
  424.  
    if (that instanceof sayHello_args)
  425.  
    return this.equals((sayHello_args)that);
  426.  
    return false;
  427.  
    }
  428.  
     
  429.  
    public boolean equals(sayHello_args that) {
  430.  
    if (that == null)
  431.  
    return false;
  432.  
     
  433.  
    boolean this_present_username = true && this.isSetUsername();
  434.  
    boolean that_present_username = true && that.isSetUsername();
  435.  
    if (this_present_username || that_present_username) {
  436.  
    if (!(this_present_username && that_present_username))
  437.  
    return false;
  438.  
    if (!this.username.equals(that.username))
  439.  
    return false;
  440.  
    }
  441.  
     
  442.  
    return true;
  443.  
    }
  444.  
     
  445.  
    @Override
  446.  
    public int hashCode() {
  447.  
    List<Object> list = new ArrayList<Object>();
  448.  
     
  449.  
    boolean present_username = true && (isSetUsername());
  450.  
    list.add(present_username);
  451.  
    if (present_username)
  452.  
    list.add(username);
  453.  
     
  454.  
    return list.hashCode();
  455.  
    }
  456.  
     
  457.  
    @Override
  458.  
    public int compareTo(sayHello_args other) {
  459.  
    if (!getClass().equals(other.getClass())) {
  460.  
    return getClass().getName().compareTo(other.getClass().getName());
  461.  
    }
  462.  
     
  463.  
    int lastComparison = 0;
  464.  
     
  465.  
    lastComparison = Boolean.valueOf(isSetUsername()).compareTo(other.isSetUsername());
  466.  
    if (lastComparison != 0) {
  467.  
    return lastComparison;
  468.  
    }
  469.  
    if (isSetUsername()) {
  470.  
    lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.username, other.username);
  471.  
    if (lastComparison != 0) {
  472.  
    return lastComparison;
  473.  
    }
  474.  
    }
  475.  
    return 0;
  476.  
    }
  477.  
     
  478.  
    public _Fields fieldForId(int fieldId) {
  479.  
    return _Fields.findByThriftId(fieldId);
  480.  
    }
  481.  
     
  482.  
    public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
  483.  
    schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
  484.  
    }
  485.  
     
  486.  
    public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
  487.  
    schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
  488.  
    }
  489.  
     
  490.  
    @Override
  491.  
    public String toString() {
  492.  
    StringBuilder sb = new StringBuilder("sayHello_args(");
  493.  
    sb.append("username:");
  494.  
    if (this.username == null) {
  495.  
    sb.append("null");
  496.  
    } else {
  497.  
    sb.append(this.username);
  498.  
    }
  499.  
    sb.append(")");
  500.  
    return sb.toString();
  501.  
    }
  502.  
     
  503.  
    public void validate() throws org.apache.thrift.TException {
  504.  
    // check for required fields
  505.  
    // check for sub-struct validity
  506.  
    }
  507.  
     
  508.  
    private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
  509.  
    try {
  510.  
    write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
  511.  
    } catch (org.apache.thrift.TException te) {
  512.  
    throw new java.io.IOException(te);
  513.  
    }
  514.  
    }
  515.  
     
  516.  
    private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
  517.  
    try {
  518.  
    read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
  519.  
    } catch (org.apache.thrift.TException te) {
  520.  
    throw new java.io.IOException(te);
  521.  
    }
  522.  
    }
  523.  
     
  524.  
    private static class sayHello_argsStandardSchemeFactory implements SchemeFactory {
  525.  
    public sayHello_argsStandardScheme getScheme() {
  526.  
    return new sayHello_argsStandardScheme();
  527.  
    }
  528.  
    }
  529.  
     
  530.  
    private static class sayHello_argsStandardScheme extends StandardScheme<sayHello_args> {
  531.  
     
  532.  
    public void read(org.apache.thrift.protocol.TProtocol iprot, sayHello_args struct) throws org.apache.thrift.TException {
  533.  
    org.apache.thrift.protocol.TField schemeField;
  534.  
    iprot.readStructBegin();
  535.  
    while (true)
  536.  
    {
  537.  
    schemeField = iprot.readFieldBegin();
  538.  
    if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
  539.  
    break;
  540.  
    }
  541.  
    switch (schemeField.id) {
  542.  
    case 1: // USERNAME
  543.  
    if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
  544.  
    struct.username = iprot.readString();
  545.  
    struct.setUsernameIsSet(true);
  546.  
    } else {
  547.  
    org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
  548.  
    }
  549.  
    break;
  550.  
    default:
  551.  
    org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
  552.  
    }
  553.  
    iprot.readFieldEnd();
  554.  
    }
  555.  
    iprot.readStructEnd();
  556.  
     
  557.  
    // check for required fields of primitive type, which can't be checked in the validate method
  558.  
    struct.validate();
  559.  
    }
  560.  
     
  561.  
    public void write(org.apache.thrift.protocol.TProtocol oprot, sayHello_args struct) throws org.apache.thrift.TException {
  562.  
    struct.validate();
  563.  
     
  564.  
    oprot.writeStructBegin(STRUCT_DESC);
  565.  
    if (struct.username != null) {
  566.  
    oprot.writeFieldBegin(USERNAME_FIELD_DESC);
  567.  
    oprot.writeString(struct.username);
  568.  
    oprot.writeFieldEnd();
  569.  
    }
  570.  
    oprot.writeFieldStop();
  571.  
    oprot.writeStructEnd();
  572.  
    }
  573.  
     
  574.  
    }
  575.  
     
  576.  
    private static class sayHello_argsTupleSchemeFactory implements SchemeFactory {
  577.  
    public sayHello_argsTupleScheme getScheme() {
  578.  
    return new sayHello_argsTupleScheme();
  579.  
    }
  580.  
    }
  581.  
     
  582.  
    private static class sayHello_argsTupleScheme extends TupleScheme<sayHello_args> {
  583.  
     
  584.  
    @Override
  585.  
    public void write(org.apache.thrift.protocol.TProtocol prot, sayHello_args struct) throws org.apache.thrift.TException {
  586.  
    TTupleProtocol oprot = (TTupleProtocol) prot;
  587.  
    BitSet optionals = new BitSet();
  588.  
    if (struct.isSetUsername()) {
  589.  
    optionals.set(0);
  590.  
    }
  591.  
    oprot.writeBitSet(optionals, 1);
  592.  
    if (struct.isSetUsername()) {
  593.  
    oprot.writeString(struct.username);
  594.  
    }
  595.  
    }
  596.  
     
  597.  
    @Override
  598.  
    public void read(org.apache.thrift.protocol.TProtocol prot, sayHello_args struct) throws org.apache.thrift.TException {
  599.  
    TTupleProtocol iprot = (TTupleProtocol) prot;
  600.  
    BitSet incoming = iprot.readBitSet(1);
  601.  
    if (incoming.get(0)) {
  602.  
    struct.username = iprot.readString();
  603.  
    struct.setUsernameIsSet(true);
  604.  
    }
  605.  
    }
  606.  
    }
  607.  
     
  608.  
    }
  609.  
     
  610.  
    //返回值
  611.  
    public static class sayHello_result implements org.apache.thrift.TBase<sayHello_result, sayHello_result._Fields>, java.io.Serializable, Cloneable, Comparable<sayHello_result> {
  612.  
    private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sayHello_result");
  613.  
     
  614.  
    private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRING, (short)0);
  615.  
     
  616.  
    private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
  617.  
    static {
  618.  
    schemes.put(StandardScheme.class, new sayHello_resultStandardSchemeFactory());
  619.  
    schemes.put(TupleScheme.class, new sayHello_resultTupleSchemeFactory());
  620.  
    }
  621.  
     
  622.  
    public String success; // required
  623.  
     
  624.  
    /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  625.  
    public enum _Fields implements org.apache.thrift.TFieldIdEnum {
  626.  
    SUCCESS((short)0, "success");
  627.  
     
  628.  
    private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
  629.  
     
  630.  
    static {
  631.  
    for (_Fields field : EnumSet.allOf(_Fields.class)) {
  632.  
    byName.put(field.getFieldName(), field);
  633.  
    }
  634.  
    }
  635.  
     
  636.  
    /**
  637.  
    * Find the _Fields constant that matches fieldId, or null if its not found.
  638.  
    */
  639.  
    public static _Fields findByThriftId(int fieldId) {
  640.  
    switch(fieldId) {
  641.  
    case 0: // SUCCESS
  642.  
    return SUCCESS;
  643.  
    default:
  644.  
    return null;
  645.  
    }
  646.  
    }
  647.  
     
  648.  
    /**
  649.  
    * Find the _Fields constant that matches fieldId, throwing an exception
  650.  
    * if it is not found.
  651.  
    */
  652.  
    public static _Fields findByThriftIdOrThrow(int fieldId) {
  653.  
    _Fields fields = findByThriftId(fieldId);
  654.  
    if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
  655.  
    return fields;
  656.  
    }
  657.  
     
  658.  
    /**
  659.  
    * Find the _Fields constant that matches name, or null if its not found.
  660.  
    */
  661.  
    public static _Fields findByName(String name) {
  662.  
    return byName.get(name);
  663.  
    }
  664.  
     
  665.  
    private final short _thriftId;
  666.  
    private final String _fieldName;
  667.  
     
  668.  
    _Fields(short thriftId, String fieldName) {
  669.  
    _thriftId = thriftId;
  670.  
    _fieldName = fieldName;
  671.  
    }
  672.  
     
  673.  
    public short getThriftFieldId() {
  674.  
    return _thriftId;
  675.  
    }
  676.  
     
  677.  
    public String getFieldName() {
  678.  
    return _fieldName;
  679.  
    }
  680.  
    }
  681.  
     
  682.  
    // isset id assignments
  683.  
    public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  684.  
    static {
  685.  
    Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
  686.  
    tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,
  687.  
    new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
  688.  
    metaDataMap = Collections.unmodifiableMap(tmpMap);
  689.  
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sayHello_result.class, metaDataMap);
  690.  
    }
  691.  
     
  692.  
    public sayHello_result() {
  693.  
    }
  694.  
     
  695.  
    public sayHello_result(
  696.  
    String success)
  697.  
    {
  698.  
    this();
  699.  
    this.success = success;
  700.  
    }
  701.  
     
  702.  
    /**
  703.  
    * Performs a deep copy on <i>other</i>.
  704.  
    */
  705.  
    public sayHello_result(sayHello_result other) {
  706.  
    if (other.isSetSuccess()) {
  707.  
    this.success = other.success;
  708.  
    }
  709.  
    }
  710.  
     
  711.  
    public sayHello_result deepCopy() {
  712.  
    return new sayHello_result(this);
  713.  
    }
  714.  
     
  715.  
    @Override
  716.  
    public void clear() {
  717.  
    this.success = null;
  718.  
    }
  719.  
     
  720.  
    public String getSuccess() {
  721.  
    return this.success;
  722.  
    }
  723.  
     
  724.  
    public sayHello_result setSuccess(String success) {
  725.  
    this.success = success;
  726.  
    return this;
  727.  
    }
  728.  
     
  729.  
    public void unsetSuccess() {
  730.  
    this.success = null;
  731.  
    }
  732.  
     
  733.  
    /** Returns true if field success is set (has been assigned a value) and false otherwise */
  734.  
    public boolean isSetSuccess() {
  735.  
    return this.success != null;
  736.  
    }
  737.  
     
  738.  
    public void setSuccessIsSet(boolean value) {
  739.  
    if (!value) {
  740.  
    this.success = null;
  741.  
    }
  742.  
    }
  743.  
     
  744.  
    public void setFieldValue(_Fields field, Object value) {
  745.  
    switch (field) {
  746.  
    case SUCCESS:
  747.  
    if (value == null) {
  748.  
    unsetSuccess();
  749.  
    } else {
  750.  
    setSuccess((String)value);
  751.  
    }
  752.  
    break;
  753.  
     
  754.  
    }
  755.  
    }
  756.  
     
  757.  
    public Object getFieldValue(_Fields field) {
  758.  
    switch (field) {
  759.  
    case SUCCESS:
  760.  
    return getSuccess();
  761.  
     
  762.  
    }
  763.  
    throw new IllegalStateException();
  764.  
    }
  765.  
     
  766.  
    /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  767.  
    public boolean isSet(_Fields field) {
  768.  
    if (field == null) {
  769.  
    throw new IllegalArgumentException();
  770.  
    }
  771.  
     
  772.  
    switch (field) {
  773.  
    case SUCCESS:
  774.  
    return isSetSuccess();
  775.  
    }
  776.  
    throw new IllegalStateException();
  777.  
    }
  778.  
     
  779.  
    @Override
  780.  
    public boolean equals(Object that) {
  781.  
    if (that == null)
  782.  
    return false;
  783.  
    if (that instanceof sayHello_result)
  784.  
    return this.equals((sayHello_result)that);
  785.  
    return false;
  786.  
    }
  787.  
     
  788.  
    public boolean equals(sayHello_result that) {
  789.  
    if (that == null)
  790.  
    return false;
  791.  
     
  792.  
    boolean this_present_success = true && this.isSetSuccess();
  793.  
    boolean that_present_success = true && that.isSetSuccess();
  794.  
    if (this_present_success || that_present_success) {
  795.  
    if (!(this_present_success && that_present_success))
  796.  
    return false;
  797.  
    if (!this.success.equals(that.success))
  798.  
    return false;
  799.  
    }
  800.  
     
  801.  
    return true;
  802.  
    }
  803.  
     
  804.  
    @Override
  805.  
    public int hashCode() {
  806.  
    List<Object> list = new ArrayList<Object>();
  807.  
     
  808.  
    boolean present_success = true && (isSetSuccess());
  809.  
    list.add(present_success);
  810.  
    if (present_success)
  811.  
    list.add(success);
  812.  
     
  813.  
    return list.hashCode();
  814.  
    }
  815.  
     
  816.  
    @Override
  817.  
    public int compareTo(sayHello_result other) {
  818.  
    if (!getClass().equals(other.getClass())) {
  819.  
    return getClass().getName().compareTo(other.getClass().getName());
  820.  
    }
  821.  
     
  822.  
    int lastComparison = 0;
  823.  
     
  824.  
    lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());
  825.  
    if (lastComparison != 0) {
  826.  
    return lastComparison;
  827.  
    }
  828.  
    if (isSetSuccess()) {
  829.  
    lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
  830.  
    if (lastComparison != 0) {
  831.  
    return lastComparison;
  832.  
    }
  833.  
    }
  834.  
    return 0;
  835.  
    }
  836.  
     
  837.  
    public _Fields fieldForId(int fieldId) {
  838.  
    return _Fields.findByThriftId(fieldId);
  839.  
    }
  840.  
     
  841.  
    public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
  842.  
    schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
  843.  
    }
  844.  
     
  845.  
    public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
  846.  
    schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
  847.  
    }
  848.  
     
  849.  
    @Override
  850.  
    public String toString() {
  851.  
    StringBuilder sb = new StringBuilder("sayHello_result(");
  852.  
    sb.append("success:");
  853.  
    if (this.success == null) {
  854.  
    sb.append("null");
  855.  
    } else {
  856.  
    sb.append(this.success);
  857.  
    }
  858.  
    sb.append(")");
  859.  
    return sb.toString();
  860.  
    }
  861.  
     
  862.  
    public void validate() throws org.apache.thrift.TException {
  863.  
    // check for required fields
  864.  
    // check for sub-struct validity
  865.  
    }
  866.  
     
  867.  
    private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
  868.  
    try {
  869.  
    write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
  870.  
    } catch (org.apache.thrift.TException te) {
  871.  
    throw new java.io.IOException(te);
  872.  
    }
  873.  
    }
  874.  
     
  875.  
    private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
  876.  
    try {
  877.  
    read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
  878.  
    } catch (org.apache.thrift.TException te) {
  879.  
    throw new java.io.IOException(te);
  880.  
    }
  881.  
    }
  882.  
     
  883.  
    private static class sayHello_resultStandardSchemeFactory implements SchemeFactory {
  884.  
    public sayHello_resultStandardScheme getScheme() {
  885.  
    return new sayHello_resultStandardScheme();
  886.  
    }
  887.  
    }
  888.  
     
  889.  
    private static class sayHello_resultStandardScheme extends StandardScheme<sayHello_result> {
  890.  
     
  891.  
    public void read(org.apache.thrift.protocol.TProtocol iprot, sayHello_result struct) throws org.apache.thrift.TException {
  892.  
    org.apache.thrift.protocol.TField schemeField;
  893.  
    iprot.readStructBegin();
  894.  
    while (true)
  895.  
    {
  896.  
    schemeField = iprot.readFieldBegin();
  897.  
    if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
  898.  
    break;
  899.  
    }
  900.  
    switch (schemeField.id) {
  901.  
    case 0: // SUCCESS
  902.  
    if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
  903.  
    struct.success = iprot.readString();
  904.  
    struct.setSuccessIsSet(true);
  905.  
    } else {
  906.  
    org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
  907.  
    }
  908.  
    break;
  909.  
    default:
  910.  
    org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
  911.  
    }
  912.  
    iprot.readFieldEnd();
  913.  
    }
  914.  
    iprot.readStructEnd();
  915.  
     
  916.  
    // check for required fields of primitive type, which can't be checked in the validate method
  917.  
    struct.validate();
  918.  
    }
  919.  
     
  920.  
    public void write(org.apache.thrift.protocol.TProtocol oprot, sayHello_result struct) throws org.apache.thrift.TException {
  921.  
    struct.validate();
  922.  
     
  923.  
    oprot.writeStructBegin(STRUCT_DESC);
  924.  
    if (struct.success != null) {
  925.  
    oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
  926.  
    oprot.writeString(struct.success);
  927.  
    oprot.writeFieldEnd();
  928.  
    }
  929.  
    oprot.writeFieldStop();
  930.  
    oprot.writeStructEnd();
  931.  
    }
  932.  
     
  933.  
    }
  934.  
     
  935.  
    private static class sayHello_resultTupleSchemeFactory implements SchemeFactory {
  936.  
    public sayHello_resultTupleScheme getScheme() {
  937.  
    return new sayHello_resultTupleScheme();
  938.  
    }
  939.  
    }
  940.  
     
  941.  
    private static class sayHello_resultTupleScheme extends TupleScheme<sayHello_result> {
  942.  
     
  943.  
    @Override
  944.  
    public void write(org.apache.thrift.protocol.TProtocol prot, sayHello_result struct) throws org.apache.thrift.TException {
  945.  
    TTupleProtocol oprot = (TTupleProtocol) prot;
  946.  
    BitSet optionals = new BitSet();
  947.  
    if (struct.isSetSuccess()) {
  948.  
    optionals.set(0);
  949.  
    }
  950.  
    oprot.writeBitSet(optionals, 1);
  951.  
    if (struct.isSetSuccess()) {
  952.  
    oprot.writeString(struct.success);
  953.  
    }
  954.  
    }
  955.  
     
  956.  
    @Override
  957.  
    public void read(org.apache.thrift.protocol.TProtocol prot, sayHello_result struct) throws org.apache.thrift.TException {
  958.  
    TTupleProtocol iprot = (TTupleProtocol) prot;
  959.  
    BitSet incoming = iprot.readBitSet(1);
  960.  
    if (incoming.get(0)) {
  961.  
    struct.success = iprot.readString();
  962.  
    struct.setSuccessIsSet(true);
  963.  
    }
  964.  
    }
  965.  
    }
  966.  
     
  967.  
    }
  968.  
     
  969.  
    }
将生成的接口HelloWorld.java复制到java工程下.
在pom.xml导入依赖jar包:
  1.  
    <dependency>
  2.  
    <groupId>org.apache.thrift</groupId>
  3.  
    <artifactId>libthrift</artifactId>
  4.  
    <version>0.9.2</version>
  5.  
    </dependency>
  6.  
    <dependency>
  7.  
    <groupId>org.slf4j</groupId>
  8.  
    <artifactId>slf4j-log4j12</artifactId>
  9.  
    <version>1.5.8</version>
  10.  
    </dependency>
3.接口实现类
接口实现类HelloWorldImpl.java:
  1.  
    package cn.slimsmart.thrift.demo.helloworld;
  2.  
     
  3.  
    import org.apache.thrift.TException;
  4.  
     
  5.  
    /**
  6.  
    * HelloWord 接口实现类
  7.  
    *
  8.  
    */
  9.  
    public class HelloWorldImpl implements HelloWorld.Iface{
  10.  
    @Override
  11.  
    public String sayHello(String username) throws TException {
  12.  
    return "hello world, "+username;
  13.  
    }
  14.  
    }
4.服务器端
服务端启动类HelloTSimpleServer.java:
  1.  
    package cn.slimsmart.thrift.demo.helloworld;
  2.  
     
  3.  
    import org.apache.thrift.TException;
  4.  
    import org.apache.thrift.TProcessor;
  5.  
    import org.apache.thrift.protocol.TBinaryProtocol;
  6.  
    import org.apache.thrift.server.TServer;
  7.  
    import org.apache.thrift.server.TSimpleServer;
  8.  
    import org.apache.thrift.transport.TServerSocket;
  9.  
     
  10.  
    /**
  11.  
    * 注册服务端 阻塞式、单线程
  12.  
    * 简单的单线程服务模型 TSimpleServer
  13.  
    */
  14.  
    public class HelloTSimpleServer {
  15.  
    // 注册端口
  16.  
    public static final int SERVER_PORT = 8080;
  17.  
     
  18.  
    public static void main(String[] args) throws TException {
  19.  
    //设置处理器
  20.  
    TProcessor tprocessor = new HelloWorld.Processor<HelloWorld.Iface>(new HelloWorldImpl());
  21.  
    // 简单的单线程服务模型,阻塞IO
  22.  
    TServerSocket serverTransport = new TServerSocket(SERVER_PORT);
  23.  
    TServer.Args tArgs = new TServer.Args(serverTransport);
  24.  
    tArgs.processor(tprocessor);
  25.  
    ////使用二进制协议
  26.  
    tArgs.protocolFactory(new TBinaryProtocol.Factory());
  27.  
    //创建服务器
  28.  
    TServer server = new TSimpleServer(tArgs);
  29.  
    System.out.println("HelloServer start....");
  30.  
    server.serve(); // 启动服务
  31.  
    }
  32.  
    }
5.客户端
客户端调用类HelloClient.java:
  1.  
    package cn.slimsmart.thrift.demo.helloworld;
  2.  
     
  3.  
    import org.apache.thrift.TException;
  4.  
    import org.apache.thrift.protocol.TBinaryProtocol;
  5.  
    import org.apache.thrift.protocol.TProtocol;
  6.  
    import org.apache.thrift.transport.TSocket;
  7.  
    import org.apache.thrift.transport.TTransport;
  8.  
     
  9.  
    /**
  10.  
    * 客户端调用HelloTSimpleServer,HelloTThreadPoolServer
  11.  
    * 阻塞
  12.  
    */
  13.  
    public class HelloClient {
  14.  
    public static final String SERVER_IP = "127.0.0.1";
  15.  
    public static final int SERVER_PORT = 8080;
  16.  
    public static final int TIMEOUT = 30000;
  17.  
     
  18.  
    public static void main(String[] args) throws TException {
  19.  
    // 设置传输通道
  20.  
    TTransport transport = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT);
  21.  
    // 协议要和服务端一致
  22.  
    //使用二进制协议
  23.  
    TProtocol protocol = new TBinaryProtocol(transport);
  24.  
    //创建Client
  25.  
    HelloWorld.Client client = new HelloWorld.Client(protocol);
  26.  
    transport.open();
  27.  
    String result = client.sayHello("jack");
  28.  
    System.out.println("result : " + result);
  29.  
    //关闭资源
  30.  
    transport.close();
  31.  
    }
  32.  
    }<strong>
  33.  
    </strong>
先运行服务端,再运行客户端,看一下运行结果吧。

posted on 2019-05-07 18:37  happy刘艺  阅读(3411)  评论(0编辑  收藏  举报

导航