Netty中的设计模式
装饰模式
-
WrappedByteBuf、UnreleasableByteBuf、SimpleLeakAwareByteBuf。第一个类就相当于装饰者父类,后两个就是装饰类,而ByteBuf就是原型。
-
class WrappedByteBuf extends ByteBuf { @Override public boolean release(int decrement) { return buf.release(decrement); } } class SimpleLeakAwareByteBuf extends WrappedByteBuf { @Override public boolean release(int decrement) { if (super.release(decrement)) { closeLeak(); return true; } return false; }
建筑者模式
-
客户端创建netty服务通常写法如下, 这里的group, channel, option , 方法就可以理解成建筑者模式的一种体现
-
//创建服务器端的启动对象 ServerBootstrap bootstrap = new ServerBootstrap(); //使用链式编程来配置参数 bootstrap.group(bossGroup, workerGroup) //设置两个线程组 .channel(NioServerSocketChannel.class) //使用NioServerSocketChannel作为服务器的通道实现 // 初始化服务器连接队列大小,服务端处理客户端连接请求是顺序处理的,所以同一时间只能处理一个客户端连接。 // 多个客户端同时来的时候,服务端将不能处理的客户端连接请求放在队列中等待处理 .option(ChannelOption.SO_BACKLOG, 1024) .childHandler(new ChannelInitializer<SocketChannel>() {//创建通道初始化对象,设置初始化参数 @Override protected void initChannel(SocketChannel ch) throws Exception { //对workerGroup的SocketChannel设置处理器 ch.pipeline().addLast(new NettyServerHandler()); } });
-
public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup) { super.group(parentGroup); ObjectUtil.checkNotNull(childGroup, "childGroup"); if (this.childGroup != null) { throw new IllegalStateException("childGroup set already"); } this.childGroup = childGroup; return this; }
-