下面主要结合实际代码来介绍一下Hadoop RPC Server端整个的处理过程:(整个核心逻辑都在org.apache.hadoop.ipc.Server这个类中实现)
首先在Server的start方法中启用相关的线程,start方法会在相关的Server中调用,如NameNode, DataNode等
public synchronized void start() {
responder.start();
listener.start();
handlers = new Handler[handlerCount];
for (int i = 0; i < handlerCount; i++) {
handlers[i] = new Handler(i);
handlers[i].start();
}
}
如上可以看到启动了listener,responer和handler threand pool,可以通过ipc.server.handler.queue.size来配置handler的个数,默认为100个。
在Server中有一个Listener的内部类,Listener的创造函数中会启动相应的Reader Thread Pool,可以通过ipc.server.read.threadpool.size来配置Reader的线程数,默认为1个。Listener会监听OP_ACCEPT事件,并在doAccpet中创建一个Connection传递给Reader,如下:
while ((channel = server.accept()) != null) {
channel.configureBlocking(false);
channel.socket().setTcpNoDelay(tcpNoDelay);
//get one reader instance for reader pool
Reader reader = getReader();
try {
//lock this reader
reader.startAdd();
SelectionKey readKey = reader.registerChannel(channel);
//build Connection instance
c = new Connection(readKey, channel, Time.now());
readKey.attach(c);
synchronized (connectionList) {
connectionList.add(numConnections, c);
numConnections++;
}
} finally {
//unlock this reader
reader.finishAdd();
}
}
}
在Reader中主要通用Connection来读取Requeset并封装成Call,读取Request分为2种处理,一种为权限读取,另一种为普通读取,具体的实现可以查看hadoop源码,这里不粘出。但是这里会介绍一下整个request在整个传送过程中的结构,request由head和conent组成。
* | "hrpc" 4 bytes |
* +----------------------------------+
* | Version (1 bytes) |
* +----------------------------------+
* | Authmethod (1 byte) |
* +----------------------------------+
* | IpcSerializationType (1 byte) |
* +----------------------------------+
if (key.channel() != call.connection.channel) {
throw new IOException("doAsyncWrite: bad channel");
}
call = responseQueue.removeFirst();
SocketChannel channel = call.connection.channel;
// Using call channel to send as much data as we can in the non-blocking fashion
int numBytes = channelWrite(channel, call.rpcResponse);
