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

如何通过Java API调用Kubernetes获取容器的资源使用情况

Hey there! I’ve built Java services that pull Kubernetes container resource metrics before, so let’s break down exactly how to do this step by step.

1. First, add the right dependencies

You’ll need the official Kubernetes Java client plus the extension for metrics APIs. If you’re using Maven, add these to your pom.xml:

<dependencies>
    <!-- Core Kubernetes Java Client -->
    <dependency>
        <groupId>io.kubernetes</groupId>
        <artifactId>client-java</artifactId>
        <version>19.0.0</version> <!-- Use the latest stable version -->
    </dependency>
    <!-- Extension for metrics.k8s.io API -->
    <dependency>
        <groupId>io.kubernetes</groupId>
        <artifactId>client-java-extended</artifactId>
        <version>19.0.0</version>
    </dependency>
</dependencies>
2. Configure the Kubernetes Client

You have two common setup scenarios:

  • Local development: Use your existing kubeconfig file (usually at ~/.kube/config)
  • Running inside the cluster: Let the client auto-detect the ServiceAccount credentials

Here’s how to initialize the client for both cases:

import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.KubeConfig;
import java.io.FileReader;

public class K8sMetricsClient {
    public static ApiClient getClient() throws Exception {
        // For local development: load kubeconfig
        String kubeConfigPath = System.getenv("HOME") + "/.kube/config";
        ApiClient client = ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))).build();
        
        // For in-cluster use: uncomment this line instead
        // ApiClient client = ClientBuilder.cluster().build();
        
        Configuration.setDefaultApiClient(client);
        return client;
    }
}
3. Fetch Container Resource Usage Metrics

Kubernetes exposes resource usage data via the metrics.k8s.io API. You’ll use the MetricsV1beta1Api (or MetricsV1Api if you’re on a newer cluster) to pull pod-level metrics, which include per-container data.

Here’s a code snippet to list metrics for all pods in a namespace:

import io.kubernetes.client.openapi.apis.MetricsV1beta1Api;
import io.kubernetes.client.openapi.models.V1beta1PodMetrics;
import io.kubernetes.client.openapi.models.V1beta1PodMetricsList;

public class ResourceUsageFetcher {
    public static void main(String[] args) throws Exception {
        ApiClient client = K8sMetricsClient.getClient();
        MetricsV1beta1Api metricsApi = new MetricsV1beta1Api(client);
        
        // Replace with your target namespace, or use "default"
        String namespace = "your-namespace";
        
        V1beta1PodMetricsList podMetricsList = metricsApi.listNamespacedPodMetrics(namespace, null, null, null, null, null, null, null, null);
        
        // Iterate through each pod's metrics
        for (V1beta1PodMetrics podMetrics : podMetricsList.getItems()) {
            System.out.println("Pod Name: " + podMetrics.getMetadata().getName());
            
            // Get metrics for each container in the pod
            podMetrics.getContainers().forEach(containerMetrics -> {
                System.out.println("  Container: " + containerMetrics.getName());
                System.out.println("    CPU Usage: " + containerMetrics.getUsage().get("cpu").getAmount() + " " + containerMetrics.getUsage().get("cpu").getUnit());
                System.out.println("    Memory Usage: " + containerMetrics.getUsage().get("memory").getAmount() + " " + containerMetrics.getUsage().get("memory").getUnit());
            });
        }
    }
}
4. Key Notes & Troubleshooting
  • Permissions: If running inside the cluster, your ServiceAccount needs permission to read metrics. Bind it to the system:metrics-reader ClusterRole with a RoleBinding.
  • Units: CPU values are often in millicores (e.g., "500m" = 0.5 cores), memory in bytes, Ki, Mi, etc. You might need to parse these into numeric values for calculations.
  • API Versions: Newer Kubernetes clusters use metrics.k8s.io/v1 instead of v1beta1—adjust the API class to MetricsV1Api if that’s the case.

Hope this gets you up and running smoothly! If you hit snags like permission denied errors or parsing issues, feel free to share more context.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 18:47:43