方式一:

直接传参数V1Namespace,参数有点麻烦

    @PostMapping("/createNamespace")
    public ResultUtil createNamespaces(@RequestBody V1Namespace body) {
        CoreV1Api apiInstance = new CoreV1Api(k8sInit.getConnection());
        String pretty = "true";
        V1Namespace result = new V1Namespace();
        try {
            result = apiInstance.createNamespace(body, pretty, null, null);
        } catch (ApiException e) {
            if(e.getCode() == 409) {
                return ResultUtil.error("409", "Error: Namespace already exists!");
            }
            if(e.getCode() == 201) {
                return ResultUtil.error("201", "Error: Namespace already exists!");
            }
            if(e.getCode() == 401) {
                return ResultUtil.error("401", "Error: No permission!");
            }
        }
        return ResultUtil.success(result);
    }

postman

POST http://localhost:8080/api/v1/namespace/createNamespace

{
	"apiVersion":"v1",
	"kind":"Namespace",
	"metadata":{
        "name":"test-namespace",
        "labels":{
            "name":"test-namespace"
        }
    }
}

kuboard上查看结果
在这里插入图片描述

方式二

发现了new V1NamespaceBuilder()创建的方式,发现了新大陆一样,只需要传一个namespace

    /**
     * 创建namespace
     * https://github.com/zq2599/blog_demos/blob/master/kubernetesclient/openapi/src/main/java/com/bolingcavalry/openapi/OpenAPIDemoApplication.java
     * @param namespace
     * @return
     */
    @GetMapping("/createNamespace2/{namespace}")
    public ResultUtil createNamespaces2(@PathVariable String namespace) {
        CoreV1Api apiInstance = new CoreV1Api(k8sInit.getConnection());

        V1Namespace v1Namespace = new V1NamespaceBuilder()
                .withNewMetadata()
                .withName(namespace)
                .endMetadata()
                .build();

        V1Namespace ns;

        try {
            ns = apiInstance.createNamespace(v1Namespace, null, null, null);
        } catch (ApiException e) {
            e.printStackTrace();
            return ResultUtil.error(String.valueOf(e.getCode()), e.getMessage());
        }
        return ResultUtil.success(ns);
    }

postman

GET http://localhost:8080/api/v1/namespace/createNamespace2/test-namespace2

在这里插入图片描述
参考

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐