官方的文檔裏一直推薦看看這三個類之間的關係. public interface ChannelPipeline extends java.lang.Iterable<java.util.Map.Entry<java.lang.String, io.netty.channel.ChannelHandler>>java
能夠看出,他裏面存的是ChannelHandler的集合 他就是一個責任鏈的設計模式實現設計模式
1.pipeline的建立 每個channel都有本身的pipeline, 而且當channel建立的時候自動建立 2.一個event是怎麼在pipeline裏流動的promise
![pipeline中事件的流動](https://static.oschina.net/uploads/img/201510/31014503_tbRZ.png "pipeline中event的流動")
3.傳遞一個事件到下一個handler ChannelHandler要想event傳遞到下一個handler,他必須調用ChannelHandlerContext的方法 1. ** Inbound event propagation methods:**安全
ChannelHandlerContext.fireChannelRegistered() ChannelHandlerContext.fireChannelActive() ChannelHandlerContext.fireChannelRead(Object) ChannelHandlerContext.fireChannelReadComplete() ChannelHandlerContext.fireExceptionCaught(Throwable) ChannelHandlerContext.fireUserEventTriggered(Object) ChannelHandlerContext.fireChannelWritabilityChanged() ChannelHandlerContext.fireChannelInactive() 2. **Outbound event propagation methods:** ChannelHandlerContext.bind(SocketAddress, ChannelPromise) ChannelHandlerContext.connect(SocketAddress, SocketAddress, ChannelPromise) ChannelHandlerContext.write(Object, ChannelPromise) ChannelHandlerContext.flush() ChannelHandlerContext.read() ChannelHandlerContext.disconnect(ChannelPromise) ChannelHandlerContext.close(ChannelPromise)
下面有一個例子async
public class MyInboundHandler extends ChannelHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) { System.out.println("Connected!"); ctx.fireChannelActive(); } } public clas MyOutboundHandler extends ChannelHandlerAdapter { @Override public void close(ChannelHandlerContext ctx, ChannelPromise promise) { System.out.println("Closing .."); ctx.close(promise); } }
如下是代碼ide
static final EventExecutorGroup group = new DefaultEventExecutorGroup(16); ... ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("decoder", new MyProtocolDecoder()); pipeline.addLast("encoder", new MyProtocolEncoder()); // Tell the pipeline to run MyBusinessLogicHandler's event handler methods // in a different thread than an I/O thread so that the I/O thread is not blocked by // a time-consuming task. // If your business logic is fully asynchronous or finished very quickly, you don't // need to specify a group. pipeline.addLast(group, "handler", new MyBusinessLogicHandler());
pipeline是線程安全的,因此一個handler能夠被添加或者刪除在任意時刻. 好比,要傳輸一些敏感的信息時,咱們能夠add一個加密的handler,用完以後remove,很方便ui