Kubernetes api微服务开发之访问api server

目标:完成对api server访问服务的开发,获取kubernetes集群当前namespacenodes

Kubernetes Java API简介

REST架构是针对Web应用而设计的,基于HTTP,目的是降低开发复杂性、提高系统可伸缩性,有如下5条准则:

  • Resource:网络上的所有事物都被抽象为资源
  • Resource Identifier:每个资源对应一个唯一的资源标识符
  • Generic Connector Interface:通过通用的连接器接口对资源进行操作
  • 对资源的各种操作不会改变资源标识符
  • Stateless:所有的操作都是无状态的

Kubernetes API定义与实现符合标准的HTTP  REST格式,是kubernetes集群中的重要组成部分。kubernetes中各种资源的数据通过API接口提交到后端持久化存储Etcd。

kubectl工具也通过API接口实现管理功能。在Master节点上执行:curl http://127.0.0.1:8080

Kubernetes有两个基于Java语言开发的开源项目:

  • Jersey
  • Fabric8

本项目使用Fabric8框架,因其对kubernetes api的封装度较高,容易实现。

主要引用的3个jar包:kubernetes-clientkubernetes-apikubernetes-model

Maven依赖

<!-- https://mvnrepository.com/artifact/io.fabric8/kubernetes-client -->
<dependency>
    <groupId>io.fabric8</groupId>
    <artifactId>kubernetes-client</artifactId>
    <version>4.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.fabric8/kubernetes-model -->
<dependency>
    <groupId>io.fabric8</groupId>
    <artifactId>kubernetes-model</artifactId>
    <version>4.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.fabric8/fabric-utils -->
<dependency>
    <groupId>io.fabric8</groupId>
    <artifactId>fabric-utils</artifactId>
    <version>2.0.47</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.fabric8/kubernetes-api -->
<dependency>
    <groupId>io.fabric8</groupId>
    <artifactId>kubernetes-api</artifactId>
    <version>3.0.12</version>
</dependency>

API调用服务编写

api调用服务的编写是项目的核心,包括初始化k8s对象,列出命令空间,列出节点3个功能。

import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class DevK8sApiService {

    //k8s api封装库调用
    private static KubernetesClient kubernetesClient;
    private static Config config;

    //初始化 - 连接k8s api server
    public String init() {
        String initResult = "Init Failed.";
        try {
            config = new ConfigBuilder().withMasterUrl("http://192.168.0.8:6443").withHttpProxy("http://119.29.172.118:8001").build();
            kubernetesClient = new DefaultKubernetesClient(config);
            initResult = "Init Success.";
            log.info("init success");
        } catch (Exception e) {
            log.error("can't init discovery service");
            log.error("", e);
        }
        return initResult;
    }

    //列出当前命名空间
    public NamespaceList listNamespace() {
        NamespaceList namespaceList = new NamespaceList();
        try {
            namespaceList = kubernetesClient.namespaces().list();
            log.info("list success");
        } catch (Exception e) {
            log.error("list failed");
            log.error("", e);
        }
        return namespaceList;
    }

    public Namespace createNamespace() {
        //ObjectMeta 配置
        Map<String, String> labels = new HashMap<>();
        labels.put("name", "AppBlog.CN");
        ObjectMeta objectMeta = new ObjectMetaBuilder().
                withName("appblog").
                withLabels(labels).
                build();
        Namespace namespace = new NamespaceBuilder().
                withApiVersion("v1").
                withKind("Namespace").
                withMetadata(objectMeta).
                build();
        try {
            //Namespace 创建
            kubernetesClient.namespaces().createOrReplace(namespace);
            log.info("namespace create success");
        } catch (Exception e) {
            log.error("namespace create failed");
            log.error("", e);
        }
        return namespace;
    }

    //列出当前可用节点
    public NodeList listNode() {
        NodeList nodeList = new NodeList();
        try {
            nodeList = kubernetesClient.nodes().list();
            log.info("list success");
        } catch (Exception e) {
            log.error("list failed");
            log.error("", e);
        }
        return nodeList;
    }

}

其中KubernetesClient与Config为Fabric8中的类。

Controller服务编写

controller服务接受外部请求,并调用后端服务,返回处理结果

import io.fabric8.kubernetes.api.model.NamespaceList;
import io.fabric8.kubernetes.api.model.NodeList;
import io.fabric8.kubernetes.api.model.Pod;
import me.yezhou.springboot.service.DevK8sApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/k8s")
public class DevK8sApiController {

    @Autowired
    private DevK8sApiService devK8sApiService;

    //k8s api init
    @RequestMapping(value = "/init", method = RequestMethod.GET)
    @ResponseBody
    public String initK8s(){
        return devK8sApiService.init();
    }

    //k8s namespace list
    @RequestMapping(value = "/list_namespace", method = RequestMethod.GET)
    @ResponseBody
    public NamespaceList listK8sNamespace(){
        return devK8sApiService.listNamespace();
    }

    //k8s namespace create
    @RequestMapping(value = "/create_namespace", method = RequestMethod.POST)
    @ResponseBody
    public Namespace createK8sNamespace() {
        return devK8sApiService.createNamespace();
    }

    //k8s node list
    @RequestMapping(value = "/list_node", method = RequestMethod.GET)
    @ResponseBody
    public NodeList listK8sNode(){
        return devK8sApiService.listNode();
    }

}
{
    "apiVersion":"v1",
    "kind":"NamespaceList",
    "metadata":{
        "resourceVersion":"201240",
        "selfLink":"/api/v1/namespaces"
    },
    "items":Array[5]
}
{
    "apiVersion": "v1",
    "kind": "Namespace",
    "metadata": {
        "annotations": {},
        "labels": {
            "name": "AppBlog.CN"
        },
        "name": "appblog"
    }
}
{
    "apiVersion":"v1",
    "kind":"NodeList",
    "metadata":{
        "resourceVersion":"201025",
        "selfLink":"/api/v1/nodes"
    },
    "items":Array[2]
}

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/23/access-api-server-for-kubernetes-api-microservice-development/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
Kubernetes api微服务开发之访问api server
目标:完成对api server访问服务的开发,获取kubernetes集群当前namespace与nodes Kubernetes Java API简介 REST架构是针对Web应用而设计的,基于HTTP,目的是……
<<上一篇
下一篇>>
文章目录
关闭
目 录