【设计模式】Netty中的设计模式

本文深入剖析Netty框架中的设计模式应用,包括建造者模式、原型模式、责任链模式和模板方法模式。通过ServerBootstrap类展示建造者模式与原型模式结合使用,使对象构建更加灵活高效;ChannelPipeline和ChannelHandlerContext的实现揭示了责任链模式如何处理I/O请求;而SimpleChannelInboundHandler则体现了模板方法模式的优雅。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 建造者模式&原型模式

应用场景:

ServerBootstrap包含多个复杂子对象需要构建,对外仅暴露一个无参构造函数,通过多个建造函数去丰富对象。同时提供私有带参构造函数来构建复制对象,仅应用于clone方法中。

public class ServerBootstrap extends AbstractBootstrap<ServerBootstrap, ServerChannel> {
    private static final InternalLogger logger = InternalLoggerFactory.getInstance(ServerBootstrap.class);
    private final Map<ChannelOption<?>, Object> childOptions = new LinkedHashMap();
    private final Map<AttributeKey<?>, Object> childAttrs = new LinkedHashMap();
    private final ServerBootstrapConfig config = new ServerBootstrapConfig(this);
    private volatile EventLoopGroup childGroup;
    private volatile ChannelHandler childHandler;

    //唯一对外开放的无参构造函数
    public ServerBootstrap() {
    }
    
    //私有带参构造函数
    private ServerBootstrap(ServerBootstrap bootstrap) {
        super(bootstrap);
        this.childGroup = bootstrap.childGroup;
        this.childHandler = bootstrap.childHandler;
        synchronized(bootstrap.childOptions) {
            this.childOptions.putAll(bootstrap.childOptions);
        }

        synchronized(bootstrap.childAttrs) {
            this.childAttrs.putAll(bootstrap.childAttrs);
        }
    }
    //构建方法
    public ServerBootstrap group(EventLoopGroup group) {
        return this.group(group, group);
    }
    //构建方法
    public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup) {
        super.group(parentGroup);
        if (childGroup == null) {
            throw new NullPointerException("childGroup");
        } else if (this.childGroup != null) {
            throw new IllegalStateException("childGroup set already");
        } else {
            this.childGroup = childGroup;
            return this;
        }
    }
    //构建方法
    public ServerBootstrap childHandler(ChannelHandler childHandler) {
        if (childHandler == null) {
            throw new NullPointerException("childHandler");
        } else {
            this.childHandler = childHandler;
            return this;
        }
    }
    //克隆方法,提供原型
    public ServerBootstrap clone() {
        return new ServerBootstrap(this);
    }
    ...
}

2 责任链

ChannelPipeline源码注释:可以说是一目了然!

 *                                                 I/O Request
 *                                            via {@link Channel} or
 *                                        {@link ChannelHandlerContext}
 *                                                      |
 *  +---------------------------------------------------+---------------+
 *  |                           ChannelPipeline         |               |
 *  |                                                  \|/              |
 *  |    +---------------------+            +-----------+----------+    |
 *  |    | Inbound Handler  N  |            | Outbound Handler  1  |    |
 *  |    +----------+----------+            +-----------+----------+    |
 *  |              /|\                                  |               |
 *  |               |                                  \|/              |
 *  |    +----------+----------+            +-----------+----------+    |
 *  |    | Inbound Handler N-1 |            | Outbound Handler  2  |    |
 *  |    +----------+----------+            +-----------+----------+    |
 *  |              /|\                                  .               |
 *  |               .                                   .               |
 *  | ChannelHandlerContext.fireIN_EVT() ChannelHandlerContext.OUT_EVT()|
 *  |        [ method call]                       [method call]         |
 *  |               .                                   .               |
 *  |               .                                  \|/              |
 *  |    +----------+----------+            +-----------+----------+    |
 *  |    | Inbound Handler  2  |            | Outbound Handler M-1 |    |
 *  |    +----------+----------+            +-----------+----------+    |
 *  |              /|\                                  |               |
 *  |               |                                  \|/              |
 *  |    +----------+----------+            +-----------+----------+    |
 *  |    | Inbound Handler  1  |            | Outbound Handler  M  |    |
 *  |    +----------+----------+            +-----------+----------+    |
 *  |              /|\                                  |               |
 *  +---------------+-----------------------------------+---------------+
 *                  |                                  \|/
 *  +---------------+-----------------------------------+---------------+
 *  |               |                                   |               |
 *  |       [ Socket.read() ]                    [ Socket.write() ]     |
 *  |                                                                   |
 *  |  Netty Internal I/O Threads (Transport Implementation)            |
 *  +-------------------------------------------------------------------+

ChannelHandlerContext:ChannelHandler的上下文,包含handler的执行环境信息,比如链表的前后节点的指针。

DefaultChannelPipeline是netty中ChannelPipeline接口的唯一实现类。我们来看看他的实现:

初始化HeadContext和TailContext:

final AbstractChannelHandlerContext head;
final AbstractChannelHandlerContext tail;

tail = new TailContext(this);
head = new HeadContext(this);

head.next = tail;
tail.prev = head;

当有新的ChannelHandlerContext加入:非常清晰的链表操作

private void addFirst0(AbstractChannelHandlerContext newCtx) {
	AbstractChannelHandlerContext nextCtx = head.next;
	newCtx.prev = head;
	newCtx.next = nextCtx;
	head.next = newCtx;
	nextCtx.prev = newCtx;
}
private void addLast0(AbstractChannelHandlerContext newCtx) {
	AbstractChannelHandlerContext prev = tail.prev;
	newCtx.prev = prev;
	newCtx.next = tail;
	prev.next = newCtx;
	tail.prev = newCtx;
}

addFirst0插在头部,addLast0插在尾部。

3 模板方法

SimpleChannelInboundHandler<I>非常典型的模板方法,直接看源码:

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	boolean release = true;
	try {
        //只接受泛型定义的msg
	    if (acceptInboundMessage(msg)) {
		Object imsg = msg;
        //子类实现处理事件逻辑
		channelRead0(ctx, imsg);
	    } else {
		release = false;
        //交由ChannelHandlerContext责任链继续处理msg
		ctx.fireChannelRead(msg);
	    }
	} finally {
        //处理结束,默认清理msg对象
	    if ((this.autoRelease) && (release))
		ReferenceCountUtil.release(msg);
	}
}

protected abstract void channelRead0(ChannelHandlerContext paramChannelHandlerContext, I paramI) throws Exception;

 

 


爱家人,爱生活,爱设计,爱编程,拥抱精彩人生!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qqchaozai

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值