本文共 2978 字,大约阅读时间需要 9 分钟。
本文是《Kubernetes 官方 Java 客户端》系列的第三篇文章。本文将介绍如何使用 Kubernetes 官方 Java 客户端(client-java.jar)在非 K8S 环境中开发一个 Spring Boot 应用。该应用通过手动复制 K8S 环境的配置文件,能够远程访问 K8S API Server 并完成客户端操作。本文将详细介绍应用的开发过程及部署方案。
本文开发的应用名为 OutsideclusterApplication,主要功能包括:
在 K8S 环境中,配置文件(kubeconfig)通常存放在用户的 ~/.kube 目录下。例如:
/Users/zhaoqin/.kube/config
在开发环境中,将该配置文件复制到应用运行所在的机器路径上(如 /Users/zhaoqin/temp/202007/05/config),供客户端使用。
该项目基于 Maven 构建,项目结构如下:
com.bolingcavalry: kubernetesclient: outsidecluster: main类:OutsideclusterApplication
项目依赖项包括:
package com.bolingcavalry.outsidecluster;import io.kubernetes.client.openapi.ApiClient;import io.kubernetes.client.openapi.Configuration;import io.kubernetes.client.openapi.apis.CoreV1Api;import io.kubernetes.client.openapi.models.V1PodList;import io.kubernetes.client.util.ClientBuilder;import io.kubernetes.client.util.KubeConfig;import lombok.extern.slf4j.Slf4j;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.io.FileReader;@SpringBootApplication@Slf4j@RestControllerpublic class OutsideclusterApplication { public static void main(String[] args) { SpringApplication.run(OutsideclusterApplication.class, args); } @RequestMapping(value = "/hello") public V1PodList hello() throws Exception { String kubeConfigPath = "/Users/zhaoqin/temp/202007/05/config"; ApiClient client = ClientBuilder .kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))) .build(); Configuration.setDefaultApiClient(client); CoreV1Api api = new CoreV1Api(); V1PodList v1PodList = api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null); log.info("pod info \n{}", new GsonBuilder().setPrettyPrinting().create().toJson(v1PodList)); return v1PodList; }} 依赖管理:通过 Maven 依赖管理,确保项目中包含所有必要的库文件。
客户端配置:使用 ClientBuilder 创建客户端实例,并加载从文件路径读取的 K8S 配置文件。
API 调用:通过 Kubernetes 官方 Java 客户端调用 CoreV1Api 类的 listPodForAllNamespaces 方法,获取所有命名空间下的 Pod 信息。
日志输出:使用 Lombok 的 Slf4j 提供日志输出功能,便于跟踪和调试。
返回数据:将获取到的 Pod 信息转换为 JSON 格式输出,供前端调用。
运行上述代码后,访问 http://localhost:8080/hello 即可获取所有 Pod 的详细信息。日志中也会打印出最新的 Pod 列表。
本文介绍了如何在非 K8S 环境中使用 Kubernetes 官方 Java 客户端开发一个 Spring Boot 应用。通过手动配置 K8S 配置文件,将客户端与 K8S API Server 连接起来。该方案适用于需要在外部环境中管理 Kubernetes 集群的场景,同时也为后续在 K8S 环境内部署客户端应用奠定了基础。
如果您不想手动编码,也可以通过 GitHub 下载完整源码。项目主页和仓库地址如下:
| 项目主页 | 无链接 | 该项目在 GitHub 的主页 |
|---|---|---|
| 无链接 | 无链接 | 无链接 |
git 仓库地址 (SSH):
git@github.com:zq2599/blog_demos.git
本文将详细介绍如何在 K8S 环境内部署客户端应用,敬请期待后续文章。
转载地址:http://kqtkz.baihongyu.com/