官方的文档里一直推荐看看这三个类之间的关系. public interface ChannelPipeline extends java.lang.Iterable<java.util.Map.Entry<java.lang.String, io.netty.channel.ChannelHandler>>
可以看出,他里面存的是ChannelHandler的集合 他就是一个责任链的设计模式实现
1.pipeline的创建 每一个channel都有自己的pipeline, 并且当channel创建的时候自动创建 2.一个event是怎么在pipeline里流动的
![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)
下面有一个例子
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);
}
}
构建一个pipeline
以下是代码
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,很方便