【Netty源码解读和权威指南】第66篇:Netty监控与可观测性——Metrics/Tracing/Logging全覆盖

发布时间:2026/6/25 16:24:17
【Netty源码解读和权威指南】第66篇:Netty监控与可观测性——Metrics/Tracing/Logging全覆盖 上一篇【第65篇】Netty优雅降级与熔断——高可用Netty服务的容错设计下一篇【第67篇】Netty Epoll传输——Linux下性能更好的原生传输层一、MicrometerPrometheus// 添加监控HandlerpublicclassMetricsHandlerextendsChannelInboundHandlerAdapter{privatefinalCounterconnectionsCounter.builder(netty.connections).register(Metrics.globalRegistry);privatefinalTimerreadTimerTimer.builder(netty.read.latency).register(Metrics.globalRegistry);publicvoidchannelActive(ChannelHandlerContextctx){connections.increment();}publicvoidchannelInactive(ChannelHandlerContextctx){connections.decrement();}publicvoidchannelRead(ChannelHandlerContextctx,Objectmsg){Timer.SamplesampleTimer.start();ctx.fireChannelRead(msg);sample.stop(readTimer);}}二、SkyWalking链路追踪// ChannelHandler集成SkyWalkingpublicclassTracingHandlerextendsChannelInboundHandlerAdapter{publicvoidchannelRead(ChannelHandlerContextctx,Objectmsg){SpanspanContextManager.createEntrySpan(netty/receive,null);span.setComponent(ComponentsDefine.NETTY);try{ContextManager.continued(span);ctx.fireChannelRead(msg);}finally{ContextManager.stopSpan();}}}三、LoggingHandler调试// Netty内置的日志Handlerpipeline.addLast(newLoggingHandler(LogLevel.INFO));// 输出格式// [id: 0x1234, L:/127.0.0.1:8080 - R:/127.0.0.1:12345] READ: 100B// [id: 0x1234, L:/127.0.0.1:8080 - R:/127.0.0.1:12345] WRITE: 50B四、关键监控指标指标类型含义netty.connections.activeGauge活跃连接数netty.read.bytesCounter读取字节数netty.write.bytesCounter写入字节数netty.read.latencyTimer读延迟netty.pool.heap.usedGauge堆内池使用量netty.pool.direct.usedGauge堆外池使用量上一篇【第65篇】Netty优雅降级与熔断——高可用Netty服务的容错设计下一篇【第67篇】Netty Epoll传输——Linux下性能更好的原生传输层