本文共 4396 字,大约阅读时间需要 14 分钟。
内容:所有原创文章分类汇总及配套源码,涉及Java、Docker、Kubernetes、DevOPS等;
名称 | 链接 | 备注 |
---|---|---|
项目主页 | 该项目在GitHub上的主页 | |
git仓库地址(https) | 该项目源码的仓库地址,https协议 | |
git仓库地址(ssh) | git@github.com:zq2599/blog_demos.git | 该项目源码的仓库地址,ssh协议 |
名为OutsideclusterApplication的应用并未部署在K8S环境,该应用能够访问到K8S环境的关键,就是将K8S环境的config文件复制一份,然后放在OutsideclusterApplication能够访问到的位置:
4.0.0 com.bolingcavalry kubernetesclient 1.0-SNAPSHOT ../pom.xml com.bolingcavalry outsidecluster 0.0.1-SNAPSHOT outsidecluster Demo project for Spring Boot jar org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-json org.projectlombok lombok true io.kubernetes client-java org.springframework.boot spring-boot-maven-plugin 2.3.0.RELEASE
package com.bolingcavalry.outsidecluster;import com.google.gson.GsonBuilder;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@RestController@Slf4jpublic class OutsideclusterApplication { public static void main(String[] args) { SpringApplication.run(OutsideclusterApplication.class, args); } @RequestMapping(value = "/hello") public V1PodList hello() throws Exception { // 存放K8S的config文件的全路径 String kubeConfigPath = "/Users/zhaoqin/temp/202007/05/config"; // 以config作为入参创建的client对象,可以访问到K8S的API Server ApiClient client = ClientBuilder .kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))) .build(); Configuration.setDefaultApiClient(client); CoreV1Api api = new CoreV1Api(); // 调用客户端API取得所有pod信息 V1PodList v1PodList = api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null); // 使用jackson将集合对象序列化成JSON,在日志中打印出来 log.info("pod info \n{}", new GsonBuilder().setPrettyPrinting().create().toJson(v1PodList)); return v1PodList; }}
运行上述代码,在浏览器访问http://localhost:8080/hello ,即可取得K8S所有pod的详情,如下所示(为了让返回数据更加整齐美观,我用的是Firefox浏览器):
查看控制台,可见日志也将详情打印出来:
微信搜索「程序员欣宸」,我是欣宸,期待与您一同畅游Java世界...
转载地址:http://kqtkz.baihongyu.com/