You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用kubernetes-client Java库获取Pod资源使用情况?

获取Pod资源使用情况(kubernetes-client Java/Scala)

核心逻辑

Kubernetes的资源使用指标是按容器维度采集的,PodMetrics类本身不提供直接的getUsage()方法,而是通过getContainers()返回Pod内所有容器的ContainerMetrics实例集合,每个ContainerMetrics包含对应容器的资源使用数据。要得到Pod的整体资源使用,只需遍历所有容器的指标并累加对应资源即可。

Scala 实现示例

基于你提供的代码修改,增加Pod级别的资源汇总逻辑:

import io.kubernetes.client.Metrics
import io.kubernetes.client.custom.PodMetricsList
import io.kubernetes.client.openapi.{ApiClient, Configuration}
import io.kubernetes.client.util.Config
import scala.jdk.CollectionConverters._
import java.util.concurrent.ConcurrentHashMap

object MetricsMonitor {
  def main(args: Array[String]): Unit = {
    val client: ApiClient = Config.defaultClient()
    Configuration.setDefaultApiClient(client)

    val metrics: Metrics = new Metrics(client)

    // 处理Pod Metrics
    val podMetricsList = metrics.getPodMetrics("boc").getItems.asScala
    podMetricsList.foreach { podMetric =>
      println(s"Pod名称: ${podMetric.getMetadata.getName}")
      println("------------------------------")

      val resourceSum = new scala.collection.mutable.HashMap[String, Long]()

      podMetric.getContainers.asScala.foreach { container =>
        println(s"容器名称: ${container.getName}")
        println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-")
        container.getUsage.asScala.foreach { case (resource, quantity) =>
          println(s"	$resource: $quantity")
          // 提取数值累加,后续统一处理单位
          val value = quantity.getAmount.toLong
          resourceSum(resource) = resourceSum.getOrElse(resource, 0L) + value
        }
        println()
      }

      // 生成Pod总资源使用(假设同类型资源单位一致)
      println("Pod总资源使用:")
      resourceSum.foreach { case (resource, totalValue) =>
        val unit = podMetric.getContainers.asScala.headOption
          .flatMap(c => Option(c.getUsage.get(resource)))
          .map(_.getSuffix).getOrElse("")
        println(s"	$resource: $totalValue$unit")
      }
      println("\n====================================\n")
    }
  }
}

Java 实现示例

逻辑与Scala一致,提供Java版本参考:

import io.kubernetes.client.Metrics;
import io.kubernetes.client.custom.ContainerMetrics;
import io.kubernetes.client.custom.PodMetrics;
import io.kubernetes.client.custom.PodMetricsList;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.util.Config;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PodMetricsMonitor {
    public static void main(String[] args) throws Exception {
        ApiClient client = Config.defaultClient();
        Configuration.setDefaultApiClient(client);
        Metrics metrics = new Metrics(client);

        PodMetricsList podMetricsList = metrics.getPodMetrics("boc");
        List<PodMetrics> items = podMetricsList.getItems();

        for (PodMetrics podMetric : items) {
            System.out.println("Pod名称: " + podMetric.getMetadata().getName());
            System.out.println("------------------------------");

            Map<String, Long> resourceSum = new HashMap<>();
            List<ContainerMetrics> containers = podMetric.getContainers();

            for (ContainerMetrics container : containers) {
                System.out.println("容器名称: " + container.getName());
                System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
                Map<String, io.kubernetes.client.custom.Quantity> usage = container.getUsage();
                for (Map.Entry<String, io.kubernetes.client.custom.Quantity> entry : usage.entrySet()) {
                    String resource = entry.getKey();
                    io.kubernetes.client.custom.Quantity quantity = entry.getValue();
                    System.out.println("\t" + resource + ": " + quantity);

                    long value = quantity.getAmount().longValue();
                    resourceSum.put(resource, resourceSum.getOrDefault(resource, 0L) + value);
                }
                System.out.println();
            }

            // 输出Pod总资源使用
            System.out.println("Pod总资源使用:");
            for (Map.Entry<String, Long> entry : resourceSum.entrySet()) {
                String resource = entry.getKey();
                long totalValue = entry.getValue();
                String unit = containers.get(0).getUsage().get(resource).getSuffix();
                System.out.println("\t" + resource + ": " + totalValue + unit);
            }
            System.out.println("\n====================================\n");
        }
    }
}

注意事项

  • 资源单位处理:示例默认同一Pod内同类型资源的单位一致,若存在单位差异,需先统一单位再进行累加计算。
  • 空值防护:若Pod无运行中容器,getContainers()可能返回空列表,需增加空值判断避免空指针异常。

内容的提问来源于stack exchange,提问作者lei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 11:45:55