Thrift server比較和使用

Thrift提供了多種服務(wù)器實現(xiàn)。

WechatIMG20.jpeg

它們各有特點,適應(yīng)不同的需求環(huán)境。下面我將結(jié)合網(wǎng)絡(luò)資源和自己的理解來梳理一下Thrift各種java server的特點和使用姿勢。

  • TSimpleServer

while (!stopped_) {
  TTransport client = null;
  TProcessor processor = null;
  TTransport inputTransport = null;
  TTransport outputTransport = null;
  TProtocol inputProtocol = null;
  TProtocol outputProtocol = null;
  ServerContext connectionContext = null;
  try {
    client = serverTransport_.accept();
    if (client != null) {
      processor = processorFactory_.getProcessor(client);
      inputTransport = inputTransportFactory_.getTransport(client);
      outputTransport = outputTransportFactory_.getTransport(client);
      inputProtocol = inputProtocolFactory_.getProtocol(inputTransport);
      outputProtocol = outputProtocolFactory_.getProtocol(outputTransport);
      if (eventHandler_ != null) {
        connectionContext = eventHandler_.createContext(inputProtocol, outputProtocol);
      }
      while (true) {
        if (eventHandler_ != null) {
          eventHandler_.processContext(connectionContext, inputTransport, outputTransport);
        }
        if(!processor.process(inputProtocol, outputProtocol)) {
          break;
        }
      }
    }
  }
}

TSimplerServer在while循環(huán)中每次接受一個連接,處理連接請求,直到客戶端關(guān)閉了連接,它才會去接受一個新的連接。由于它只在一個單獨的線程中以阻塞I/O的方式完成這些工作,所以它只能服務(wù)一個客戶端連接,其他所有客戶端在被服務(wù)器端接受之前都只能等待。其使用方法如下:

public static void sample() throws Exception {
    ServerSocket socket = new ServerSocket(8912);
    TServerSocket serverTransport = new TServerSocket(socket); // HelloServiceImpl 為自己實現(xiàn)的Thrift服務(wù)接口的具體實現(xiàn)  
    TServer server = new TSimpleServer(new TServer.Args(serverTransport).processor(processor));
    System.out.println("Server start...");
    server.serve();
}
  • TNonblockingServer

public void run() {
  try {
    if (eventHandler_ != null) {
      eventHandler_.preServe();
    }

    while (!stopped_) {
      select();
      processInterestChanges();
    }
    for (SelectionKey selectionKey : selector.keys()) {
      cleanupSelectionKey(selectionKey);
    }
  } catch (Throwable t) {
    LOGGER.error("run() exiting due to uncaught error", t);
  } finally {
    try {
      selector.close();
    } catch (IOException e) {
      LOGGER.error("Got an IOException while closing selector!", e);
    }
    stopped_ = true;
  }
}
private void select() {
  try {
    // wait for io events.
    selector.select();

    // process the io events we received
    Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
    while (!stopped_ && selectedKeys.hasNext()) {
      SelectionKey key = selectedKeys.next();
      selectedKeys.remove();

      // skip if not valid
      if (!key.isValid()) {
        cleanupSelectionKey(key);
        continue;
      }

      // if the key is marked Accept, then it has to be the server
      // transport.
      if (key.isAcceptable()) {
        handleAccept();
      } else if (key.isReadable()) {
        // deal with reads
        handleRead(key);
      } else if (key.isWritable()) {
        // deal with writes
        handleWrite(key);
      } else {
        LOGGER.warn("Unexpected state in select! " + key.interestOps());
      }
    }
  } catch (IOException e) {
    LOGGER.warn("Got an IOException while selecting!", e);
  }
}

TNonblockingServer 使用非阻塞的 I/O 解決了TSimpleServer一個客戶端阻塞其他所有客戶端的問題。它使用了java.nio.channels.Selector,通過調(diào)用select(),它使得你阻塞在多個連接上,而不是阻塞在單一的連接上。當(dāng)一或多個連接準(zhǔn)備好被接受/讀/寫時,select()調(diào)用便會返回。TNonblockingServer處理這些連接的時候,要么接受它,要么從它那讀數(shù)據(jù),要么把數(shù)據(jù)寫到它那里,然后再次調(diào)用select()來等待下一個可用的連接。通用這種方式,server可同時服務(wù)多個客戶端,而不會出現(xiàn)一個客戶端把其他客戶端全部“餓死”的情況。
使用方法:

public static void nonBlock() throws TTransportException {
    TNonblockingServerSocket serverSocket = new TNonblockingServerSocket(8912);
    Hello.Processor processor = new Hello.Processor(new HelloServiceImpl());
    TNonblockingServer.Args args = new TNonblockingServer.Args(serverSocket);
    args.transportFactory(new TFramedTransport.Factory());
    args.protocolFactory(new TCompactProtocol.Factory());
    args.processor(processor);
    TNonblockingServer server = new TNonblockingServer(args);
    server.serve();
}
  • ThreadedSelectorServer

ThreadedSelectorServer允許你用多個線程來處理網(wǎng)絡(luò) I/O。它維護(hù)了兩個線程池,一個用來處理網(wǎng)絡(luò) I/O,另一個用來進(jìn)行請求的處理。使用方法:

public static void threadSelector() throws TTransportException, IOException {
    TNonblockingServerSocket serverSocket = new TNonblockingServerSocket(8912);
    Hello.Processor processor = new Hello.Processor(new HelloServiceImpl());
    TThreadedSelectorServer.Args args = new TThreadedSelectorServer.Args(serverSocket);
    args.transportFactory(new TFramedTransport.Factory());
    args.protocolFactory(new TBinaryProtocol.Factory());
    args.selectorThreads(10);
    args.acceptQueueSizePerThread(10);
    args.processor(processor);
    TThreadedSelectorServer server = new TThreadedSelectorServer(args);
    server.serve();
}
  • TThreadPoolServer

TThreadPoolServer有一個專用的線程用來接受連接旦接受了一個連接,它就會被放入ThreadPoolExecutor中的一個 worker 線程里處理。worker 線程被綁定到特定的客戶端連接上,直到它關(guān)閉。一旦連接關(guān)閉,該worker線程就又回到了線程池中。你可以配置線程池的最小、最大線程數(shù),默認(rèn)值分別是5(最?。┖虸nteger.MAX_VALUE(最大)。使用方法:

public static void threadPool() throws Exception {
    TNonblockingServerSocket serverSocket = new TNonblockingServerSocket(8912);
    Hello.Processor processor = new Hello.Processor(new HelloServiceImpl());
    TThreadPoolServer.Args args = new TThreadPoolServer.Args(serverSocket);
    args.transportFactory(new TFramedTransport.Factory());
    args.protocolFactory(new TBinaryProtocol.Factory());
    args.processor(processor);
    args.maxWorkerThreads(10);
    TThreadPoolServer server = new TThreadPoolServer(args);
    server.serve();
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 聊聊阻塞與非阻塞、同步與異步、I/O 模型 來源:huangguisu 鏈接:http://blog.csdn.n...
    meng_philip123閱讀 1,746評論 1 13
  • NIO(Non-blocking I/O,在Java領(lǐng)域,也稱為New I/O),是一種同步非阻塞的I/O模型,也...
    閃電是只貓閱讀 3,277評論 0 7
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,692評論 18 399
  • 我以前就是一個淘寶購物狂,經(jīng)常是沒有時間出門,上班沒有假期所以,慢慢就成了淘寶購物狂。什么東西都喜歡網(wǎng)上購...
    一朵白薔薇閱讀 184評論 0 0
  • 下雨天,很冷,就要穿厚點兒也要記得帶傘。不要讓自己那么狼狽,所有能預(yù)先知道的事情,你就要有所準(zhǔn)備。你明明更新過天氣...
    92b1602690b6閱讀 423評論 0 0

友情鏈接更多精彩內(nèi)容