38

学习 Kubernetes(十七):Java 客户端

 4 years ago
source link: https://www.tuicool.com/articles/qYvUZnm
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

kube-apiserver 是 Kubernetes 唯一操作 etcd 的组件,并对外提供 REST API 与 Kubernetes 进行交互。

Vjm2632.png!web

同时,官方和社区封装了 REST API ,提供了各个编程语言版本的客户端库,其中就包括了 Java 版本 kubenetes-client

依赖

执行命令 kubectl version 查看 Kubernetes 集群版本,并对照官方提供的 兼容性 表格,使用合适的版本。

例如:Kubernetes v1.11.x 集群可以使用 >= 3.0.0 客户端。

编辑 pom.xml 文件,添加依赖:

<dependency>  
    <groupId>io.kubernetes</groupId>
    <artifactId>client-java</artifactId>
    <version>5.0.0</version>
</dependency>

举:chestnut:

1. 加载配置

在 macOS 系统中,配置文件通常位于 ~/.kube/config。拷贝文件到 Java 工程 src/main/resources 目录下,并重命名为 config.yaml。

创建加载 Classpath 文件工具方法:

static Reader readFromClasspath(String path) {  
    ClassLoader classLoader = Application.class.getClassLoader();
    InputStream in = classLoader.getResourceAsStream(path);
    return new InputStreamReader(in);
}

2. 初始化客户端

ApiClient client;  
try (Reader reader = readFromClasspath("config.yaml")) {  
    client = ClientBuilder
            .kubeconfig(KubeConfig.loadKubeConfig(reader))
            .build(); // ①
}
Configuration.setDefaultApiClient(client); // ②

① 创建客户端;

② 配置全局默认的客户端。

3. 集群交互

客户端创建完毕,就可以和 Kubernetes 进行交互了。

以创建 Job 为例,更多实例参考 Kubernetes API Reference Docs

BatchV1Api api = new BatchV1Api(); // ①  
try (Reader reader = readFromClasspath("job.yaml")) {  
    V1Job job = (V1Job) Yaml.load(reader); // ②
    api.createNamespacedJob("default", job, null, null, null); // ③
}

① 创建 API 对象;

② 通过 YAML 文件创建请求参数;

③ 调用 api-server 创建资源。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK