Netty客户端Handler
在 Netty 配置客户端端时,添加的真正处理业务逻辑的 NettyClientHandler 。
概述
NettyClientHandler 继承 ChannelInboundHandlerAdapter,覆写 channelRead、userEventTriggered、exceptionCaught三个方法。
channelRead :处理服务端返回的数据,交由 CompletableFuture返回(下一篇会讲到 CompletableFuture)给代理方法。
userEventTriggered:对Netty心跳检测事件进行处理,几秒没有写操作的话,发送一个心跳信息过去,以防止服务端关闭ctx。
exceptionCaught:处理异常。
实现代码
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
log.info("client receive msg : [{}]", msg);
if (msg instanceof RpcResponse) {
RpcResponse<Object> rpcResponse = (RpcResponse<Object>) msg;
unprocessedRequests.complete(rpcResponse);
}
} finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleState state = ((IdleStateEvent) evt).state();
if (state == IdleState.WRITER_IDLE) {
log.info("write idle happen [{}]", ctx.channel().remoteAddress());
Channel channel = channelProvider.get((InetSocketAddress) ctx.channel().remoteAddress());
RpcRequest rpcRequest = RpcRequest.builder().rpcMessageType(RpcMessageType.HEART_BEAT).build();
channel.writeAndFlush(rpcRequest).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
}
} else {
super.userEventTriggered(ctx, evt);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
}
版权声明:本文为gutou__yu原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。