Netty 源码分析系列之Netty 编码器,不吃透都对不起自己

本文详细介绍了Netty框架中的MessageToByteEncoder接口和其实现原理,重点讲解了encode方法在编码过程中的作用,以及如何通过子类如ShortToByteEncoder进行消息编码。还提到了MessageToMessageEncoder的用途和其在性能优化中的角色。

protected MessageToByteEncoder(Class<? extends I> outboundMessageType) {

this(outboundMessageType, true);

}

protected MessageToByteEncoder(boolean preferDirect) {

this.matcher = TypeParameterMatcher.find(this, MessageToByteEncoder.class, “I”);

this.preferDirect = preferDirect;

}

protected MessageToByteEncoder(Class<? extends I> outboundMessageType, boolean preferDirect) {

this.matcher = TypeParameterMatcher.get(outboundMessageType);

this.preferDirect = preferDirect;

}

public boolean acceptOutboundMessage(Object msg) throws Exception {

return this.matcher.match(msg);

}

public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {

ByteBuf buf = null;

try {

if (this.acceptOutboundMessage(msg)) {

I cast = msg;

buf = this.allocateBuffer(ctx, msg, this.preferDirect);

try {

this.encode(ctx, cast, buf);

} finally {

ReferenceCountUtil.release(msg);

}

if (buf.isReadable()) {

ctx.write(buf, promise);

} else {

buf.release();

ctx.write(Unpooled.EMPTY_BUFFER, promise);

}

buf = null;

} else {

ctx.write(msg, promise);

}

} catch (EncoderException var17) {

throw var17;

} catch (Throwable var18) {

throw new EncoderException(var18);

} finally {

if (buf != null) {

buf.release();

}

}

}

protected ByteBuf allocateBuffer(ChannelHandlerContext ctx, I msg, boolean preferDirect) throws Exception {

return preferDirect ? ctx.alloc().ioBuffer() : ctx.alloc().heapBuffer();

}

protected abstract void encode(ChannelHandlerContext var1, I var2, ByteBuf var3) throws Exception;

protected boolean isPreferDirect() {

return this.preferDirect;

}

}

复制代码

在MessageToByteEncoder抽象类中,唯一要关注的是encode方法,该方法是开发者需要实现的唯一抽象方法。它与出站消息一起调用,将消息编码为ByteBuf,然后,将ByteBuf转发到ChannelPipeline中的下一个ChannelOutboundHandler。

以下是MessageToByteEncoder 的使用示例:

public class ShortToByteEncoder extends MessageToByteEncoder {

@Override

protected void encode(ChannelHandlerContext ctx, Integer msg, ByteBuf out) throws Exception {

out.writeShort(msg);//将Short转成二进制字节流写入ByteBuf中

}

}

复制代码

上述示例中,ShortToByteEncoder收到 Short 消息,编码它们,并把它们写入ByteBuf。然后,将ByteBuf转发到ChannelPipeline中的下一个ChannelOutboundHandler,每个 Short 将占有 ByteBuf 的两个字节。

实现ShortToByteEncoder主要分为以下两步:

  • 实现继承自MessageToByteEncoder。

  • 写 Short 到 ByteBuf。

上述的例子处理流程图如下:

Netty 源码分析系列(十三)Netty 编码器

Netty 也提供了很多MessageToByteEncoder类的子类来帮助开发者实现自己的编码器,例如:

Netty 源码分析系列(十三)Netty 编码器

MessageToMessageEncoder 抽象类

===========================

MessageToMessageEncoder 抽象类用于将出站数据从一种消息转换为另一种消息

核心源码如下:

public abstract class MessageToMessageEncoder extends ChannelOutboundHandlerAdapter {

private final TypeParameterMatcher matcher;

/**

  • Create a new instance which will try to detect the types to match out of the type parameter of the class.

*/

protected MessageToMessageEncoder() {

matcher = TypeParameterMatcher.find(this, MessageToMessageEncoder.class, “I”);

}

/**

  • Create a new instance

  • @param outboundMessageType The type of messages to match and so encode

*/

protected MessageToMessageEncoder(Class<? extends I> outboundMessageType) {

matcher = TypeParameterMatcher.get(outboundMessageType);

}

/**

  • Returns {@code true} if the given message should be handled. If {@code false} it will be passed to the next

  • {@link ChannelOutboundHandler} in the {@link ChannelPipeline}.

*/

public boolean acceptOutboundMessage(Object msg) throws Exception {

return matcher.match(msg);

}

@Override

public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {

CodecOutputList out = null;

try {

if (acceptOutboundMessage(msg)) {

out = CodecOutputList.newInstance();

@SuppressWarnings(“unchecked”)

I cast = (I) msg;

try {

encode(ctx, cast, out);

} finally {

ReferenceCountUtil.release(cast);

}

if (out.isEmpty()) {

throw new EncoderException(

StringUtil.simpleClassName(this) + " must produce at least one message.");

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数前端工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Web前端开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加V获取:vip1024c (备注前端)
img

性能优化

1.webpack打包文件体积过大?(最终打包为一个js文件)

2.如何优化webpack构建的性能

3.移动端的性能优化

4.Vue的SPA 如何优化加载速度

5.移动端300ms延迟

6.页面的重构

所有的知识点都有详细的解答,我整理成了280页PDF《前端校招面试真题精编解析》。

CodeChina开源项目:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】


3221732119.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2h1Z28yMzM=,size_16,color_FFFFFF,t_70)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值