【Netty源码解读和权威指南】第53篇:Netty在Dubbo中的应用——Dubbo网络通信层深度解析
2026/6/26 4:33:01 网站建设 项目流程

上一篇【第52篇】Netty秒杀系统——高并发网络接入层实战
下一篇【第54篇】Netty在Elasticsearch中的应用——分布式搜索引擎的网络通信


一、Dubbo网络通信架构

+------------------+ +------------------+ | Consumer | | Provider | | (NettyClient) | | (NettyServer) | +------------------+ +------------------+ | Transport层 | | Transport层 | | Exchange层 | | Exchange层 | | Protocol层 | | Protocol层 | +------------------+ +------------------+ | | +----------------------+ | Dubbo协议(基于Netty)

二、Dubbo协议格式

Dubbo RPC协议帧: +------+------+------+------+------+------+------+------+ | 魔数(0xdabb,2B) | 标志位(1B) | 状态(1B) | ID(8B) | +------+------+------+------+------+------+------+------+ | 数据长度(4B) | +------+------+------+------+------+------+------+------+ | 序列化数据(body, variable) | +------+------+------+------+------+------+------+------+

标志位含义

  • bit 0-2:序列化类型(0=Hessian, 2=JSON, 6=Kryo, 8=Protobuf)
  • bit 3-4:事件类型(0=Request, 1=Response, 2=心跳)
  • bit 5:是否双向通信
  • bit 6-7:保留

三、NettyServer初始化

// Dubbo 3.x中的NettyServerpublicclassNettyServerextendsAbstractServer{protectedvoiddoOpen(){bootstrap=newServerBootstrap();bootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).childOption(ChannelOption.TCP_NODELAY,true).childOption(ChannelOption.SO_KEEPALIVE,true).childHandler(newChannelInitializer<SocketChannel>(){protectedvoidinitChannel(SocketChannelch){// Dubbo编解码器ch.pipeline().addLast("decoder",newDubboCountCodec());ch.pipeline().addLast("encoder",newDubboCountCodec());// Dubbo业务处理器ch.pipeline().addLast("handler",newNettyServerHandler());}});ChannelFuturef=bootstrap.bind(getBindAddress());}}

四、Dubbo编解码器

// DubboCodec = 长度字段编解码 + Dubbo协议publicclassDubboCodecextendsExchangeCodec{protectedvoidencodeRequestData(Channelchannel,Objectoutput,ByteBufbuffer){// 序列化RPC调用数据:dubbo版本、服务名、方法名、参数等RpcInvocationinv=(RpcInvocation)output;ObjectOutputout=CodecSupport.getSerialization(channel.getUrl()).serialize(channel.getUrl(),buffer);out.writeUTF(inv.getAttachment(DUBBO_VERSION_KEY));out.writeUTF(inv.getAttachment(PATH_KEY));// 服务名out.writeUTF(inv.getAttachment(VERSION_KEY));out.writeUTF(inv.getMethodName());// 方法名out.writeUTF(inv.getParameterTypesDesc());// 参数类型// 写入参数值for(Objectarg:inv.getArguments()){out.writeObject(arg);}}}

五、Dubbo心跳机制

// 客户端发送心跳publicclassHeartbeatTimerTaskimplementsRunnable{publicvoidrun(){if(System.currentTimeMillis()-lastReadTime>heartbeat){// 发送心跳请求Requestreq=newRequest();req.setVersion(Version.getProtocolVersion());req.setTwoWay(true);req.setEvent(Request.HEARTBEAT_EVENT);channel.send(req);}}}// 服务端响应心跳if(request.isHeartbeat()){Responseresponse=newResponse();response.setEvent(Response.HEARTBEAT_EVENT);channel.send(response);return;}

六、总结

组件作用
NettyServer/NettyClientTransport层实现
DubboCodecDubbo协议编解码
ExchangeHandler请求-响应模型
心跳机制60秒空闲检测

上一篇【第52篇】Netty秒杀系统——高并发网络接入层实战
下一篇【第54篇】Netty在Elasticsearch中的应用——分布式搜索引擎的网络通信


需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询