如何通过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.
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>
You have two common setup scenarios:
- Local development: Use your existing
kubeconfigfile (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; } }
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()); }); } } }
- Permissions: If running inside the cluster, your ServiceAccount needs permission to read metrics. Bind it to the
system:metrics-readerClusterRole 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/v1instead ofv1beta1—adjust the API class toMetricsV1Apiif 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

