final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
channels = nettyHandler.getChannels();
// https://issues.jboss.org/browse/NETTY-365
// https://issues.jboss.org/browse/NETTY-379
// final Timer timer = new HashedWheelTimer(new NamedThreadFactory(“NettyIdleTimer”, true));
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() {
NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast(“decoder”, adapter.getDecoder()); // @start
pipeline.addLast(“encoder”, adapter.getEncoder());
pipeline.addLast(“handler”, nettyHandler); // @end
return pipeline;
}
});
可以看出,传入Netty框架的事件处理Handler主要是3个:1、解码器;2、编码器;3、业务类NettyHandler。也就是说当服务端(Server)的读事件就绪后,进行网络读写后,会将二进制流传入解码器(Decoder),解码出一个一个的RPC请求,然后针对每一个RPC请求,交给NettyHandler相关事件处理方法去处理,在这里传入NettyHandler的ChannelHandler为NettyServer,以网络读命令为例,最终将调用NettyServer的父类AbstractPeer的received方法:
@Override
public void received(Channel ch, Object msg) throws RemotingException {
if (closed) {
return;
}
handler.received(ch, msg);
}
那AbstractPeer中的ChannelHandler又是“何许人也”,是通过调用NettyServer(URL url, ChannelHandler handler)中传入的,结合上图中NettyServer的构建流程,可以追溯其流程如下:
- DubboProtocol#createServer
server = Exchangers.bind(url, requestHandler); // @1, requestHandler,为最原始的ChannelHandler,接下来整个过程都是对该handler的包装。
- HeaderExchanger#bind
return new HeaderExchangeServer(Transporters.bind(url, new
DecodeHandler(new HeaderExchangeHandler(handler))));其包装顺序为 DecodeHandler 》HeaderExchangeHandler 》(DubboProtocol#requestHandler)
-
NettyTransporter#bind
-
NettyServer构造函数
super(url, ChannelHandlers.wrap(handler, ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME)));这里主要包装的是事件的派发Handler,例如AllChannelHandler、ExecutionChannelHandler【Dispatch】业务Handler最终的包装顺序为:事件派发模型handler[AllChannelHandler] 》DecodeHandler 》HeaderExchangeHandler 》 DubboProtocol#requestHandler(最终的业务Handler)。结合网络Netty的处理Handler,服务端事件Handler的处理为:DubboCodec2(解码器) 》 事件派发模型handler[AllChannelHandler] 》DecodeHandler 》 HeaderExchangeHandler》 Dubbo