Thrift採用了TServer来作为server的抽象,提供了多种类型的server实现。用TServerTransport作为server的Acceptor抽象,来监听端口。创建clientSocket连接
先来看看TServerTransport。主要有两类
1. TNonblockingServerTransport和TNonblockingServerSocket作为非堵塞IO的Acceptor,封装了ServerSocketChannel
2. TServerSocket作为堵塞同步IO的Acceptor,封装了ServerSocket
public class TNonblockingServerSocket extends TNonblockingServerTransport { private ServerSocketChannel serverSocketChannel = null; } protected TNonblockingSocket acceptImpl() throws TTransportException { if (serverSocket_ == null) { throw new TTransportException(TTransportException.NOT_OPEN, "No underlying server socket."); } try { SocketChannel socketChannel = serverSocketChannel.accept(); if (socketChannel == null) { return null; } TNonblockingSocket tsocket = new TNonblockingSocket(socketChannel); tsocket.setTimeout(clientTimeout_); return tsocket; } catch (IOException iox) { throw new TTransportException(iox); } } public void registerSelector(Selector selector) { try { // Register the server socket channel, indicating an interest in // accepting new connections serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); } catch (ClosedChannelException e) { // this shouldn‘t happen, ideally... // TODO: decide what to do with this. } } public class TServerSocket extends TServerTransport { private ServerSocket serverSocket_ = null; } protected TSocket acceptImpl() throws TTransportException { if (serverSocket_ == null) { throw new TTransportException(TTransportException.NOT_OPEN, "No underlying server socket."); } try { Socket result = serverSocket_.accept(); TSocket result2 = new TSocket(result); result2.setTimeout(clientTimeout_); return result2; } catch (IOException iox) { throw new TTransportException(iox); } }
再看TServer的类层次结构。主要也是两类,非堵塞IO和同步IO
非堵塞IO的Server有:
1. TNonblockingServer是单线程的,仅仅有一个SelectAcceptThread线程来轮询IO就绪事件,调用就绪的channel来对应Accept, Read, Write事件。而且还是使用这个线程来同步调用实际的方法实现。
2. THsHaServer是所谓的半同步半异步的server。所谓半同步是说使用一个SelectAcceptThread线程来轮询IO就绪事件,调用就绪的channel来对应Accept, Read, Write事件。所谓的半异步是说方法的调用是封装成一个Runnable交给线程池来运行的,交给线程池立马返回,不同步等待方法运行完成,方法运行完成的写返回是有线程池中的线程来做的,实现了所谓的异步訪问的模式。
3. TThreadSelectorServer,这个server类比較有意思。是多线程Reactor模式的一种实现。
3.1 採用了一个AcceptorThread来专门监听port,处理Accept事件,然后创建SocketChannel。创建完毕之后交给一个线程池来处理兴许动作,将SocketChannel放到SelecotrThread的堵塞队列acceptedQueue中
3.2 採用多个SelectorThread来处理创建好的SocketChannel。每一个SelectorThread绑定一个Selector。这样将SocketChannel分给多个Selector。
同一时候SelectorThread又维护了一个堵塞队列acceptedQueue,从acceptedQueue中拿新创建好的SocketChannel,来注冊读事件
同步的TServer有TThreadPoolServer,关联一个TServerSocket,採用同步IO的方式来Accept,然后交给一个线程池来处理兴许动作
这里有一篇老外写的文章比較各种server的性能。https://github.com/m1ch1/mapkeeper/wiki/Thrift-Java-Servers-Compared
结论是TThreadSelectorServer在吞吐量和server响应时间的表现都是最优的