Java 模擬 k8s Deployment 操作 7.0.0

先導(dǎo)入 k8s 官方 jdk 7.0.0 版本

        <dependency>
            <groupId>io.kubernetes</groupId>
            <artifactId>client-java</artifactId>
            <version>7.0.0</version>
        </dependency>

創(chuàng)建 Deployment 操作 簡單示例

    @Test
    public void createNamespacedDeployment(){
        AppsV1Api apiInstance = new AppsV1Api(DeploymentTest.getApiClient());
        String namespace = "test-namespace"; // namespace
        String name = "test-deployment";
        //插入 端口暴露服務(wù)的 對應(yīng)的是 Service.Spec.Selector 下的值
        Map<String,String> selectLabels = new HashMap<>();
        selectLabels.put("select-name","test-deployment");
        V1Deployment body = new V1DeploymentBuilder()
                .withMetadata(new V1ObjectMetaBuilder()
                        .withName(name)
                        .withNamespace(namespace)
                        .withLabels(selectLabels)
                        .build())
                .withSpec(new V1DeploymentSpecBuilder()
                        //設(shè)置默認副本數(shù)
                        .withReplicas(1)
                        //設(shè)置選擇器
                        .withSelector(new V1LabelSelectorBuilder()
                                .withMatchLabels(selectLabels)
                                .build())
                        //設(shè)置docker模板
                        .withTemplate(new V1PodTemplateSpecBuilder()
                                .withMetadata(new V1ObjectMetaBuilder()
                                        .withLabels(selectLabels)
                                        .build())
                                .withSpec(new V1PodSpecBuilder()
                                        .withContainers(new V1ContainerBuilder()
                                                .withName("test-nginx")//設(shè)置docker名
                                                .withImage("nginx")//設(shè)置 docker鏡像名
                                                .withPorts(new V1ContainerPortBuilder()
                                                        .withContainerPort(80)//設(shè)置內(nèi)部端口
                                                        .withProtocol("TCP")//連接方式
                                                        .build())
                                                .build())
                                        .build())
                                .build())
                        .build())
                .build(); // V1Deployment |
        String pretty = null; // 是否會漂亮輸出
        String dryRun = null; //
        String fieldManager = null; //
        try {
            V1Deployment result = apiInstance.createNamespacedDeployment(namespace, body, pretty, dryRun, fieldManager);
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling AppsV1Api#createNamespacedDeployment");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
    }

還有

listNamespacedDeployment //根據(jù)namespace 查詢其下所有 deployment
readNamespacedDeployment //根據(jù)namespace 與 name 查詢指定的 deployment
deleteNamespacedDeployment//根據(jù)namespace 與 name 刪除指定deployment
patchNamespacedDeployment//根據(jù)namespace 與 name 修復(fù)填充新的參數(shù)或設(shè)置項
replaceNamespaceDeployment//根據(jù) namespce 與 name 替換相關(guān)配置
注:以上就不 贅述了 看看 官方 api 文檔截止到怎么操作了

重點來了

眾所周知 deployment 不管有著以上操作 還有一下內(nèi)容

  • 版本回退
  • 彈性伸縮
  • 設(shè)置卷(物理卷或虛擬卷)
  • 重新部署

仔細一看可以發(fā)現(xiàn) 官方的 AppsV1Api 中沒有相關(guān)操作
經(jīng)過我仔細研究與發(fā)現(xiàn)找到 還不是正式版本的Api 鏘! 鏘 !鏘!ExtensionsV1beta1Api 該api雖然還沒有正式版但是 該api 下的
ExtensionsV1beta1Deployment中的ExtensionsV1beta1DeploymentSpec有著 相關(guān)操作 下面附上官方md


ExtensionsV1beta1DeploymentSpec.jpg

可以看到 這里面就有咱們需要用到的 ,例如:

  1. 暫停與開始 paused
  2. 版本回退 rollbackTo
  3. 升級策略 strategy(滾動更新或替換更新)

其實這個 api 中我覺的最有用的 就是 上面這三個
廢話不多說 上代碼

 @Test
    public void replaceNamespaceDeployment() {
        //獲取對象操作
        ExtensionsV1beta1Api apiInstance = new ExtensionsV1beta1Api(DeploymentTest.getApiClient());
        String name = "test-deployment";
        String namespace = "test-namespace"; // namespace
        String storeName = "test-store";//卷名 虛擬卷名
        String pretty = null; // String | If 'true', then the output is pretty printed.
        Boolean exact = null; // Boolean | Should the export be exact.  Exact export maintains cluster-specific fields like 'Namespace'. Deprecated. Planned for removal in 1.18.
        Boolean export = null; // Boolean | Should this value be exported.  Export strips fields that a user can not specify. Deprecated. Planned for removal in 1.18.
        String dryRun = null; // String | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
        String fieldManager = null; // String | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
        try {
            //獲取需要修改的 deployment 對象
            ExtensionsV1beta1Deployment body = apiInstance.readNamespacedDeployment(name, namespace, pretty, exact, export);
            //輸出 deployment 對象
            System.out.println("body = " + body);
            //暫停/繼續(xù) deployment
//            body.getSpec().setPaused(true);
//            body.getSpec().setPaused(false);
            //添加環(huán)境變量
//            body.getSpec().getTemplate().getSpec().getContainers().forEach(i->{
//                List<V1EnvVar> list = new ArrayList<>();
//                list.add(new V1EnvVarBuilder()
//                        .withName("TEST-ENV")
//                        .withValue("There is only one truth")//真想只有一個 致敬死神小學(xué)生
//                        .build());
//                //添加環(huán)境到每一個模板中
//                i.setEnv(list);
//            });
            //重新部署
//            body.getSpec().getTemplate().getMetadata().getAnnotations().put("kubesphere.io/restartedAt",new DateTime().toString());
            //指定卷
//            List<V1Volume> v1Volumes = new ArrayList<>();
//            v1Volumes.add(new V1VolumeBuilder()
//                    //指定虛擬卷
//                    .withName(storeName)
//                    //指定實體卷
////                    .withEmptyDir()
//                    .build());
//            body.getSpec().getTemplate().getSpec().setVolumes(v1Volumes);
//            body.getSpec().getTemplate().getSpec().getContainers().forEach(i->{
//                List<V1VolumeMount> v1VolumeMounts = new ArrayList<>();
//                v1VolumeMounts.add(new V1VolumeMountBuilder()
//                        .withName(storeName)
//                        //掛載路徑
//                        .withMountPath("/date")
//                        .build());
//                i.setVolumeMounts(v1VolumeMounts);
//            });
            //指定版本回退
            body.getSpec().setRollbackTo(new ExtensionsV1beta1RollbackConfigBuilder()
                    //回滾到指定版本
                    .withRevision(1L)
                    .build());
            //怎么查看歷史版本號請  查看官方文檔 有關(guān) AppsV1Api 下的 listNamespaceReplicaSet 方法 具體操作 官方文檔中有
            ExtensionsV1beta1Deployment result = apiInstance.replaceNamespacedDeployment(name, namespace, body, pretty, dryRun, fieldManager);
            //輸出修改后的 deployment 對象
            System.out.println("result = " + result);
        } catch (ApiException e) {
            System.err.println("Exception when calling ExtensionsV1beta1Api#readNamespacedDeployment");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容