Use kubernetes-client/java class library to implement java calls to k8s api

Create a new maven project and introduce dependencies

My k8s version is 1.5, so I introduced the 7.0.0 version

    <dependencies>
        <dependency>
            <groupId>io.kubernetes</groupId>
            <artifactId>client-java</artifactId>
            <version>7.0.0</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

Copy the k8s config file to the project

Download ~/.kube/config via ftp and put it under the project.

 

ftp

 

config

Create a new test file

import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodList;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.KubeConfig;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class TestClient {
    public static void main(String[] args) throws ApiException, IOException, ApiException {
        //直接写config path
        String kubeConfigPath = "config";

        //加载k8s, config
        ApiClient client = ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))).build();

        //将加载config的client设置为默认的client
        Configuration.setDefaultApiClient(client);

        //创建一个api
        CoreV1Api api = new CoreV1Api();

        //打印所有的pod
        V1PodList list = api.listPodForAllNamespaces(null,null,null,null,null,null,null,
        null,null);

        for (V1Pod item : list.getItems()) {
            System.out.println(item);
        }
    }
}

 

Guess you like

Origin blog.csdn.net/litianquan/article/details/108984385