名为OutsideclusterApplication的应用并未部署在K8S环境,该应用能够访问到K8S环境的关键,就是将K8S环境的config文件复制一份,然后放在OutsideclusterApplication能够访问到的位置:
登录K8S环境,在~/.kube目录下找到config文件,复制此文件到OutsideclusterApplication运行的机器上(我这里存放的路径是/Users/zhaoqin/temp/202007/05/,和后面的代码中一致);
打开《Kubernetes官方java客户端:准备》中创建的的kubernetesclient工程,在里面创建子工程,名为OutsideclusterApplication,这是个SpringBoot工程,pom.xml内容如下:
<project xmlns=“http://maven.apache.org/POM/4.0.0” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=“http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd”>
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.R
《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》
【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享
ELEASE
上述pom.xml中,需要注意的是在依赖spring-boot-starter-web的时候,使用exclusion语法排除了spring-boot-starter-json的依赖,这样做是为了将jackson的依赖全部去掉(spring-boot-starter-json依赖了jackson),如此一来整个classpath下面就没有了jackson库,此时SpringBoot框架就会使用gson作为序列化和反序列化工具(client-java.jar依赖了gson库);(这个问题在《Kubernetes官方java客户端之二:序列化和反序列化问题》一文有详细介绍)
新增OutsideclusterApplication.java,简单起见,该类即是引导类又是Controller:
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
@Slf4j
public 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();