基于 Netty 活跃连接数自定义 Prometheus 指标适配 HPA?

解读

国内云原生面试里,这道题把“Netty 内核指标暴露”与“K8s 弹性伸缩”两条高频主线拧在一起,既考你对 Netty 生命周期细节的掌握,也验证你是否能把业务指标无缝接入 Prometheus + HPA 体系。面试官通常分三层追问:

  1. 你怎么在 Netty 里拿到“真·活跃连接”而不是“曾经创建过”?
  2. 指标怎么透出到 Prometheus?push 还是 pull?端口、路径、性能、安全怎么权衡?
  3. HPA 的算法只认整数,QPS 类指标可以瞬时抖动,连接数相对平滑,你怎么配阈值、冷却窗口、防止抖动?

回答必须给出可落地的 Java 代码片段、配套的 ServiceMonitor/PodMonitor 样板以及 HPA 的 YAML 关键字段,缺一步都会被判“不接地气”。

知识点

  1. Netty 连接生命周期:ChannelActive、ChannelInactive、ChannelFutureListener.CLOSE 等事件回调顺序,以及异常断开时是否保证触发 inactive。
  2. 指标原子性:高并发下不能用普通 long,必须用 LongAdder 或 AtomicLongFieldUpdater 做无锁累加,防止多线程可见性问题。
  3. Micrometer + Prometheus Java Client 双栈:Micrometer 可以一步导出到 Prometheus,也能桥接到 Spring Boot Actuator;纯 Netty 项目无 Spring 时,直接用 prometheus-client-hotspot 更轻量。
  4. pull 模型规范:端口必须与业务端口分离,路径统一 /metrics,Content-Type 用 text/plain; version=0.0.4;k8s 内通过 ServiceMonitor 让 Prometheus 自动发现。
  5. HPA 配置细节:metrics.type=Pods,target.type=AverageValue,averageValue 用“连接数/副本数”做均值;同时设置 stabilizationWindowSeconds、scaleUp/scaleDown 的 policies 防止毛刺。
  6. 零拷贝与性能:指标采集逻辑必须放在自定义 ChannelInboundHandler 的 userEventTriggered 里,避免在 read 链路上加锁;prometheus scrape 走独立 EventLoopGroup,防止拉取阻塞 IO 线程。

答案

下面给出可直接拷贝到生产的最小闭环示例,假设项目为“im-gateway”,跑在阿里云 ACK 集群 1.24+,Prometheus 用 ACK 托管版,HPA 版本 autoscaling/v2。

  1. Netty 端代码(无 Spring,纯 Java 17)
public final class ConnectionMetricsHandler extends ChannelInboundHandlerAdapter {
    private static final LongAdder ACTIVE = new LongAdder();
    private static final Counter TOTAL  = Counter.build()
            .name("netty_connection_total")
            .help("累计连接数")
            .register();
    static final Gauge ACTIVE_GAUGE = Gauge.build()
            .name("netty_connection_active")
            .help("当前活跃连接")
            .register();

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        ACTIVE.increment();
        ACTIVE_GAUGE.set(ACTIVE.sum());
        TOTAL.inc();
        ctx.fireChannelActive();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        ACTIVE.decrement();
        ACTIVE_GAUGE.set(ACTIVE.sum());
        ctx.fireChannelInactive();
    }
}

在 ServerBootstrap 的 childHandler 里加入 new ConnectionMetricsHandler() 即可。

  1. 独立 MetricsServer(端口 8081,路径 /metrics)
EventLoopGroup metricsGroup = new NioEventLoopGroup(1);
ServerBootstrap b = new ServerBootstrap();
b.group(metricsGroup)
 .channel(NioServerSocketChannel.class)
 .childHandler(new ChannelInitializer<SocketChannel>() {
     @Override
     protected void initChannel(SocketChannel ch) {
         ch.pipeline().addLast(new HttpServerCodec(),
                               new HttpObjectAggregator(512),
                               new SimpleChannelInboundHandler<FullHttpRequest>() {
             @Override
             protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) {
                 if (!req.uri().equals("/metrics")) {
                     ctx.fireChannelRead(req.retain());
                     return;
                 }
                 ByteBuf buf = Unpooled.wrappedBuffer(CollectorRegistry.defaultRegistry
                                                          .filteredMetricFamilySamples(Set.of())
                                                          .getBytes(StandardCharsets.UTF_8));
                 FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                                                                       HttpResponseStatus.OK, buf);
                 resp.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; version=0.0.4");
                 ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
             }
         });
     }
 });
b.bind(8081).sync();
  1. Dockerfile 暴露 8081
EXPOSE 8080 8081

Deployment 里给 8081 起名 metrics-port,并加 annotation:

prometheus.io/scrape: "true"
prometheus.io/port:   "8081"
prometheus.io/path:   "/metrics"
  1. ServiceMonitor(ACK 托管 Prometheus 已集成)
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: im-gateway
spec:
  selector:
    matchLabels:
      app: im-gateway
  endpoints:
  - port: metrics-port
    interval: 15s
    path: /metrics
  1. HPA
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: im-gateway
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: im-gateway
  minReplicas: 2
  maxReplicas: 60
  metrics:
  - type: Pods
    pods:
      metric:
        name: netty_connection_active
      target:
        type: AverageValue
        averageValue: "1000"   # 每个副本 1000 条连接
  behavior:
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
      - type: Pods
        value: 2
        periodSeconds: 60
    scaleUp:
      stabilizationWindowSeconds: 30
      policies:
      - type: Pods
        value: 8
        periodSeconds: 30

这样当平均活跃连接数 >1000 时,HPA 会在 30 秒内最多扩容 8 个 Pod;连接下降后冷却 5 分钟才缩容,防止抖动。

拓展思考

  1. 连接数≠负载:长连接场景下,连接数平稳但单连接 QPS 可能突增。可再暴露一个 netty_msg_per_second{direction="in"} 指标,用 PromQL 做加权:0.7*connection_active + 0.3*msg_rate 作为自定义指标,让 HPA 更贴合真实负载。
  2. 多协议端口:Netty 可能同时开 443、80、8000 三个端口,连接数需按端口打 label,HPA 可针对“总连接”或“单端口连接”分别配置。
  3. 连接染色:在 Channel 的 AttributeKey 里标记“业务类型”(IM、MQTT、GRPC),Micrometer 的 Gauge 构造时把 tag 带上,HPA 就能对“高价值 IM 连接”单独扩容。
  4. 大集群优化:prometheus-client 默认内存采样全部指标,高并发下 8081 端口可能成为热点。可开启“openmetrics”压缩输出,或把指标先写本地内存队列,再异步聚合,降低 scrape 延迟。
  5. 安全合规:金融场景下 8081 不能对外暴露,通过 Istio Sidecar 做 mTLS,只允许 Prometheus 走 15090 端口拉取;或者使用 pushgateway 推送到内网网关,避免业务端口裸奔。