歡迎訪問我的GitHub
https://github.com/zq2599/blog_demos
內容:所有原創文章分類匯總及配套原始碼,涉及Java、Docker、Kubernetes、DevOPS等;
概覽
- 本文是《Kubernetes官方java客戶端》系列的第六篇,以下提到的java客戶端都是指client-jar.jar;
- 前文《Kubernetes官方java客戶端之五:proto基本操作 》已經提到,java客戶端的基本功能由兩個主要脈絡組成,第一個是proto,主要功能是使用ProtoClient類提供的增刪改查介面,這些介面用到的入參和回傳物件所涉及到的java類,都是通過K8S的protobuf生成的;
- 除了使用ProtoClient對K8S資源進行增刪改查,還提供了另一種更強大的方式:OpenAPI,本章咱們就來一起學習OpenAPI相關的操作;
K8S的OpenAPI
-
先拋開java客戶端不提,咱們來看看K8S本身的OpenAPI,地址是:https://kubernetes.io/zh/docs/concepts/overview/kubernetes-api/ ,關鍵資訊如下圖所示,可見K8S提供了OpenAPI規范:

-
如果您想查看當前K8S環境的OpenAPI規范,請打開K8S環境的/etc/kubernetes/manifests/kube-apiserver.yaml檔案,增加下圖紅框中的內容:

-
修改完畢后請稍候,系統會根據檔案的變化自動更新(千萬不要執行kubectl apply -f kube-apiserver.yaml,這會導致新建api-server的pod,由于埠占用而啟動失敗);
-
假設宿主機IP地址是192.168.50.135,那么在瀏覽器上訪問:http://192.168.50.135:8080/openapi/v2,就能得到所有OpenAPI資訊如下圖:

-
上圖的原始資料沒有可讀性,復制到在線JSON格式化網站,得到的內容如下圖,例如查詢pod串列的API資訊已經非常詳細了:

-
以上就是對K8S的OpenAPI簡介,接下來回到java客戶端本身,看看它提供了哪些OpenAPI相關的能力;
java客戶端的OpenAPI
-
打開java客戶端工程的原始碼如下圖,紅框1就是和OpenAPI相關的子工程,提供服務的功能類都在紅框2的package中,也就是說,依靠紅框2中的API以及紅框3中的資料結構,我們可以完成大部分K8S資源控制相關的操作:

-
打開常用的CoreV1Api.java,如下圖紅框,頂部的注釋已經說明了一切:這些代碼都是工具生成的(至于如何生成就不在本文中討論了):

-
如果您下載了java客戶端原始碼,可以在client-java-api這個子工程中看到完整的OpenAPI介面檔案:

-
前文《Kubernetes官方java客戶端之五:proto基本操作 》的代碼中,咱們嘗試過獲取pod串列,但是ProtoClient的已有API不支持提交更詳細的業務引數,此時選擇OpenAPI介面即可輸入詳細的業務引數,介面詳細資訊可以在檔案中查到,還帶有完整的demo代碼,如下圖所示:

-
上圖中的listNamespacedPod介面有兩個重要引數:fieldSelector和labelSelector,這是過濾用的,詳細的用法請參考K8S官方檔案,地址是:https://kubernetes.io/docs/concepts/overview/working-with-objects/ ,如下圖紅框:

-
弄清楚了K8S的OpenAPI規范,以及java客戶端依據此規范生成的API服務,還有詳細的介面檔案在手,可以編碼實戰了;
原始碼下載
- 如果您不想編碼,可以在GitHub下載所有原始碼,地址和鏈接資訊如下表所示(https://github.com/zq2599/blog_demos):
| 名稱 | 鏈接 | 備注 |
|---|---|---|
| 專案主頁 | https://github.com/zq2599/blog_demos | 該專案在GitHub上的主頁 |
| git倉庫地址(https) | https://github.com/zq2599/blog_demos.git | 該專案原始碼的倉庫地址,https協議 |
| git倉庫地址(ssh) | [email protected]:zq2599/blog_demos.git | 該專案原始碼的倉庫地址,ssh協議 |
- 這個git專案中有多個檔案夾,本章的應用在kubernetesclient檔案夾下,如下圖紅框所示:

開始編碼
- 打開《Kubernetes官方java客戶端之一:準備 》中創建的kubernetesclient工程,在里面新建子工程openapi,其pom.xml內容如下,要注意的是spring-boot-starter-json已經被排除,因此序列化工具會變為Gson(原本默認是jackson):
<?xml version="1.0" encoding="UTF-8"?>
<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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.bolingcavalry</groupId>
<artifactId>kubernetesclient</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<groupId>com.bolingcavalry</groupId>
<artifactId>openapi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>openapi</name>
<description>Demo project for openapi client</description>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.kubernetes</groupId>
<artifactId>client-java</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.0.RELEASE</version>
</plugin>
</plugins>
</build>
</project>
- 新增OpenAPIDemoApplication.java,這是新工程的引導類,也有兩個web介面,一個創建namespace,另一個按照namespace查詢pod串列,關鍵位置已添加了注釋,就不多贅述了:
package com.bolingcavalry.openapi;
import com.google.gson.GsonBuilder;
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.V1Namespace;
import io.kubernetes.client.openapi.models.V1NamespaceBuilder;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.PostConstruct;
import java.io.FileReader;
@SpringBootApplication
@RestController
@Slf4j
public class OpenAPIDemoApplication {
public static void main(String[] args) {
SpringApplication.run(OpenAPIDemoApplication.class, args);
}
/**
* 默認的全域設定
* @return
* @throws Exception
*/
@PostConstruct
private void setDefaultApiClient() 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);
}
@RequestMapping(value = "https://www.cnblogs.com/openapi/createnamespace/{namespace}", method = RequestMethod.GET)
public V1Namespace createnamespace(@PathVariable("namespace") String namespace) throws Exception {
CoreV1Api coreV1Api = new CoreV1Api();
V1Namespace v1Namespace = new V1NamespaceBuilder()
.withNewMetadata()
.withName(namespace)
.endMetadata()
.build();
V1Namespace ns = coreV1Api.createNamespace(v1Namespace, null, null, null);
// 使用Gson將集合物件序列化成JSON,在日志中列印出來
log.info("ns info \n{}", new GsonBuilder().setPrettyPrinting().create().toJson(ns));
return ns;
}
@RequestMapping(value = "https://www.cnblogs.com/openapi/pods/{namespace}", method = RequestMethod.GET)
public V1PodList pods(@PathVariable("namespace") String namespace) throws ApiException {
CoreV1Api apiInstance = new CoreV1Api();
// String | If 'true', then the output is pretty printed.
String pretty = null;
// 訂閱事件相關的引數,這里用不上
Boolean allowWatchBookmarks = false;
// 連續查找的標志,類似于翻頁
String _continue = null;
// 欄位選擇器
String fieldSelector = "status.phase=Running";
// 根據標簽過濾
// String labelSelector = "component=kube-apiserver";
String labelSelector = null;
Integer limit = null;
String resourceVersion = null;
Integer timeoutSeconds = null;
Boolean watch = false;
V1PodList v1PodList = apiInstance.listNamespacedPod(namespace,
pretty,
allowWatchBookmarks,
_continue,
fieldSelector,
labelSelector,
limit,
resourceVersion,
timeoutSeconds,
watch);
// 使用Gson將集合物件序列化成JSON,在日志中列印出來
log.info("pod info \n{}", new GsonBuilder().setPrettyPrinting().create().toJson(v1PodList));
return v1PodList;
}
}
-
將OpenAPIDemoApplication運行起來,先測驗創建namespace的服務,在瀏覽器訪問:http://localhost:8080/openapi/createnamespace/dddeeefff ,瀏覽器回傳資訊如下圖:

-
SSH登錄K8S主機,執行命令查看namespace,如下圖紅框,已經創建成功:

- 再試試Pod串列,地址是 :http://localhost:8080/openapi/pods/kube-system ,如下圖:

- 至此,OpenAPI介面的實踐就完成了,現在已將java客戶端的最基本的功能都實踐過了,接下來的文章咱們將開始學習精彩的高級功能;
你不孤單,欣宸原創一路相伴
- Java系列
- Spring系列
- Docker系列
- kubernetes系列
- 資料庫+中間件系列
- DevOps系列
歡迎關注公眾號:程式員欣宸
微信搜索「程式員欣宸」,我是欣宸,期待與您一同暢游Java世界...
https://github.com/zq2599/blog_demos
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/247048.html
標籤:Java
上一篇:4 大軟體架構,你們公司用哪種?
