关于云计算:Kubernetes官方java客户端之六OpenAPI基本操作

欢送拜访我的GitHub

https://github.com/zq2599/blog_demos

内容:所有原创文章分类汇总及配套源码,波及Java、Docker、Kubernetes、DevOPS等;

概览

  1. 本文是《Kubernetes官网java客户端》系列的第六篇,以下提到的<font color=”blue”>java客户端</font>都是指<font color=”red”>client-jar.jar</font>;
  2. 前文《Kubernetes官网java客户端之五:proto基本操作 》曾经提到,java客户端的基本功能由两个次要脉络组成,第一个是<font color=”blue”>proto</font>,次要性能是应用<font color=”blue”>ProtoClient</font>类提供的增删改查接口,这些接口用到的入参和返回对象所波及到的java类,都是通过K8S的protobuf生成的;
  3. 除了应用ProtoClient对K8S资源进行增删改查,还提供了另一种更弱小的形式:OpenAPI,本章咱们就来一起学习OpenAPI相干的操作;

K8S的OpenAPI

  1. 先抛开java客户端不提,咱们来看看K8S自身的OpenAPI,地址是:https://kubernetes.io/zh/docs… ,要害信息如下图所示,可见K8S提供了OpenAPI标准:

  1. 如果您想查看以后K8S环境的OpenAPI标准,请关上K8S环境的/etc/kubernetes/manifests/kube-apiserver.yaml文件,减少下图红框中的内容:

  1. 批改结束后请稍候,零碎会依据文件的变动自动更新(<font color=”red”>千万不要执行kubectl apply -f kube-apiserver.yaml</font>,这会导致新建api-server的pod,因为端口占用而启动失败);
  2. 假如宿主机IP地址是192.168.50.135,那么在浏览器上拜访:http://192.168.50.135:8080/openapi/v2,就能失去所有OpenAPI信息如下图:

  1. 上图的原始数据没有可读性,复制到在线JSON格式化网站,失去的内容如下图,例如查问pod列表的API信息曾经十分具体了:

  1. 以上就是对K8S的OpenAPI简介,接下来回到<font color=”blue”>java客户端</font>自身,看看它提供了哪些OpenAPI相干的能力;

java客户端的OpenAPI

  1. 关上java客户端工程的源码如下图,红框1就是和OpenAPI相干的子工程,提供服务的性能类都在红框2的package中,也就是说,依附红框2中的API以及红框3中的数据结构,咱们能够实现大部分K8S资源管制相干的操作:

  1. 关上罕用的<font color=”blue”>CoreV1Api.java</font>,如下图红框,顶部的正文曾经阐明了所有:这些代码都是工具生成的(至于如何生成就不在本文中探讨了):

  1. 如果您下载了java客户端源码,能够在client-java-api这个子工程中看到残缺的OpenAPI接口文档:

  1. 前文《Kubernetes官网java客户端之五:proto基本操作 》的代码中,咱们尝试过获取pod列表,然而ProtoClient的已有API不反对提交更具体的业务参数,此时抉择OpenAPI接口即可输出具体的业务参数,接口详细信息能够在文档中查到,还带有残缺的demo代码,如下图所示:

  1. 上图中的<font color=”blue”>listNamespacedPod</font>接口有两个重要参数:<font color=”red”>fieldSelector</font>和<font color=”red”>labelSelector</font>,这是过滤用的,具体的用法请参考K8S官网文档,地址是:https://kubernetes.io/docs/co… ,如下图红框:

  1. 弄清楚了K8S的OpenAPI标准,以及java客户端根据此标准生成的API服务,还有具体的接口文档在手,能够编码实战了;

源码下载

  1. 如果您不想编码,能够在GitHub下载所有源码,地址和链接信息如下表所示(https://github.com/zq2599/blo…:
名称 链接 备注
我的项目主页 https://github.com/zq2599/blo… 该我的项目在GitHub上的主页
git仓库地址(https) https://github.com/zq2599/blo… 该我的项目源码的仓库地址,https协定
git仓库地址(ssh) git@github.com:zq2599/blog_demos.git 该我的项目源码的仓库地址,ssh协定
  1. 这个git我的项目中有多个文件夹,本章的利用在<font color=”blue”>kubernetesclient</font>文件夹下,如下图红框所示:

开始编码

  1. 关上[《Kubernetes官网java客户端之一:筹备 》]()中创立的<font color=”blue”>kubernetesclient</font>工程,在外面新建子工程<font color=”red”>openapi</font>,其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>
  1. 新增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 = "/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 = "/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;
    }

}
  1. 将<font color=”blue”>OpenAPIDemoApplication</font>运行起来,先测试创立<font color=”blue”>namespace</font>的服务,在浏览器拜访:http://localhost:8080/openapi/createnamespace/dddeeefff ,浏览器返回信息如下图:

  1. SSH登录K8S主机,执行命令查看namespace,如下图红框,曾经创立胜利:

  1. 再试试Pod列表,地址是 :http://localhost:8080/openapi/pods/kube-system ,如下图:

  • 至此,OpenAPI接口的实际就实现了,当初已将java客户端的最根本的性能都实际过了,接下来的文章咱们将开始学习精彩的高级性能;

你不孤独,欣宸原创一路相伴

  1. Java系列
  2. Spring系列
  3. Docker系列
  4. kubernetes系列
  5. 数据库+中间件系列
  6. DevOps系列

欢送关注公众号:程序员欣宸

微信搜寻「程序员欣宸」,我是欣宸,期待与您一起畅游Java世界…
https://github.com/zq2599/blog_demos

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理