概要
用过Netty的小伙伴都知道, 当我们使用了Netty, 就意味着我们使用了Netty…就意味着我们不仅需要处理业务数据, 还需要围绕 连接(Channel) 来添加相当一部分的逻辑, 比如断线重连, 心跳, 重试,读闲置, 写闲置,超时等等进行设置, 此部分的逻辑一般不建议和业务处理器耦合在一起,不仅可读性差, 难维护, 还会引发歧义, 为此Nettyx提供了InboundAdvice和OutboundAdvice来解决此类问题
TIPS: 建议将InboundAdvice放在Pipeline的末尾, OutboundAdvice放在Pipeline开头
那正文开始了, 先引入Nettyx的依赖
请从maven中央仓获取{lastest.version},最新版本号
<dependency>
<groupId>io.github.fbbzl</groupId>
<artifactId>nettyx</artifactId>
<version>{lastest.version}</version>
</dependency>
InboundAdvice
InboundAdvice内部提供了很多 函数字段, 即field类型为函数接口.且名称都以when开头,比如whenChannelInactive,whenChannelActive等等
以下将展示如何通过InboundAdvice简单实现断线重连
private ChannelInitializer<NioSocketChannel> channelInitializer() {
return new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel channel) {
InboundAdvice inboundAdvice = new InboundAdvice(channel);
// 每当断开连接的时候, 都会触发whenChannelInactive, 你可以在此方法中执行重连逻辑
inboundAdvice.whenChannelInactive(ctx -> Console.print("invoke your re-connect method here"));
channel.pipeline()
// in out
// ▼ ▲ remove start and end flag
.addLast(new StartEndFlagFrameCodec(1024 * 1024, false, Unpooled.wrappedBuffer(new byte[]{(byte) 0x7e})))
.addLast(new EscapeCodec(EscapeMap.mapHex("7e", "7d5e")))
.addLast(new UserCodec())
// ▼ ▲ deal control character and recover application data
.addLast(new LoggerHandler.InboundLogger(log, LoggerHandler.Sl4jLevel.ERROR))
// 建议把inboundAdvice 放在pipeline末尾, 不然会提前触发对应的方法!!!
.addLast(inboundAdvice); }
};
}
至此我们完成了一个简单的基于InboundAdvice的断线重连
OutboundAdvice
OutboundAdvice一样是通过lambda表达式来进行增强的, 包括方法命名都很类似,使用也很类似, 唯一要注意的是, 它们在pipeline中的位置, 个人建议InboundAdvice放在pipelien末尾, OutboundAdvice放在pipelien首位
private ChannelInitializer<NioSocketChannel> channelInitializer() {
return new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel channel) {
InboundAdvice inboundAdvice = new InboundAdvice(channel);
// 入栈建言, 上面已经讲过
inboundAdvice.whenChannelInactive(ctx -> Console.print("invoke your re-connect method here"));
// 出站建言
OutboundAdvice outboundAdvice = new OutboundAdvice(channel);
// 当disconenct时执行 指定的方法
outboundAdvice.whenDisconnect((ctx, promise) -> Console.print("invoke your disconnect method"));
channel.pipeline()
//outboundadvice建议放在开头!!!!!
.addLast(outboundAdvice)
// in out
// ▼ ▲ remove start and end flag
.addLast(new StartEndFlagFrameCodec(1024 * 1024, false, Unpooled.wrappedBuffer(new byte[]{(byte) 0x7e})))
.addLast(new EscapeCodec(EscapeMap.mapHex("7e", "7d5e")))
.addLast(new UserCodec())
// ▼ ▲ deal control character and recover application data
.addLast(new LoggerHandler.InboundLogger(log, LoggerHandler.Sl4jLevel.ERROR))
//放在末尾的inboundadvice
.addLast(inboundAdvice);
}
};
}
==========================================================================
至此完成了对Nettyx中消息建言初步的使用介绍