官方的文档里一直推荐看看这三个类之间的关系. 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

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