1. 概述
在本文,我们来分享 SimpleChannelInboundHandler 处理器。考虑到 SimpleUserEventChannelHandler 和 SimpleChannelInboundHandler 的实现基本一致,所以也会在本文中分享。
如果胖友对 SimpleChannelInboundHandler 的使用不了解,请先看下 《一起学Netty(三)之 SimpleChannelInboundHandler》 ,嘿嘿。
2. SimpleChannelInboundHandler
io.netty.channel.SimpleChannelInboundHandler
,继承 ChannelInboundHandlerAdapter 类,抽象类,处理指定类型的消息。应用程序中,我们可以实现 SimpleChannelInboundHandler 后,实现对指定类型的消息的自定义处理。
2.1 构造方法
public abstract class SimpleChannelInboundHandler<I> extends ChannelInboundHandlerAdapter { |
matcher
属性,有两种方式赋值。- 【常用】
<1>
处,使用类的I
泛型对应的 TypeParameterMatcher 类型匹配器。 <2>
处,使用inboundMessageType
参数对应的 TypeParameterMatcher 类型匹配器。- 在大多数情况下,我们不太需要特别详细的了解
io.netty.util.internal.TypeParameterMatcher
的代码实现,感兴趣的胖友可以自己看看 《netty 简单Inbound通道处理器(SimpleChannelInboundHandler)》 的 「TypeParameterMatcher」 部分。
- 【常用】
autoRelease
属性,使用完消息,是否自动释放。
2.2 acceptInboundMessage
#acceptInboundMessage(Object msg)
方法,判断消息是否匹配。代码如下:
/** |
一般情况下,matcher
的类型是 ReflectiveMatcher( 它是 TypeParameterMatcher 的内部类 )。代码如下:
private static final class ReflectiveMatcher extends TypeParameterMatcher { |
- 匹配逻辑,看
<1>
处,使用Class#isInstance(Object obj)
方法。对于这个方法,如果我们定义的I
泛型是个父类,那可以匹配所有的子类。例如I
设置为 Object 类,那么所有消息,都可以被匹配列。
2.3 channelRead
1: |
- 第 4 行:
release
属性,是否需要释放消息。 第 7 行:调用
#acceptInboundMessage(Object msg)
方法,判断是否为匹配的消息。① 匹配,调用
#channelRead0(ChannelHandlerContext ctx, I msg)
抽象方法,处理消息。代码如下:/**
* <strong>Please keep in mind that this method will be renamed to
* {@code messageReceived(ChannelHandlerContext, I)} in 5.0.</strong>
*
* Is called for each message of type {@link I}.
*
* @param ctx the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
* belongs to
* @param msg the message to handle
* @throws Exception is thrown if an error occurred
*/
protected abstract void channelRead0(ChannelHandlerContext ctx, I msg) throws Exception;- 子类实现 SimpleChannelInboundHandler 类后,实现该方法,就能很方便的处理消息。
- ② 不匹配,标记不需要释放消息,并触发 Channel Read 到下一个节点。
- 第 18 至 23 行:通过
release
变量 +autoRelease
属性,判断是否需要释放消息。若需要,调用ReferenceCountUtil#release(Object msg)
方法,释放消息。😈 还是蛮方便的。
3. SimpleUserEventChannelHandler
io.netty.channel.SimpleUserEventChannelHandler
,继承 ChannelInboundHandlerAdapter 类,抽象类,处理指定事件的消息。
SimpleUserEventChannelHandler 和 SimpleChannelInboundHandler 基本一致,差别在于将指定类型的消息,改成了制定类型的事件。😈 所以,笔者就不详细解析了。
代码如下:
public abstract class SimpleUserEventChannelHandler<I> extends ChannelInboundHandlerAdapter { |
666. 彩蛋
木有彩蛋,hoho 。