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>
先運行服務端,再運行客戶端,看一下運行結果吧。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM