项目实用 java调用k8s

如果操作k8s找对应的api太难 就试试我这万能的方法吧

可以解决k8s外部相关框架接口 如 tfjob,padd,pytchon等 一个万能api

maven安装依赖

  <!--        调用k8s-->
        <dependency>
            <groupId>io.kubernetes</groupId>
            <artifactId>client-java</artifactId>
            <version>5.0.0</version>
        </dependency>

相关配置文件

1.加载yml文件

import com.ruoyi.web.fzzn.k8s.controller.K8sServiceController;
import io.kubernetes.client.ApiClient;
import io.kubernetes.client.Configuration;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.Config;
import io.kubernetes.client.util.KubeConfig;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.FileReader;

@Component
public class K8sConfig {
    @Value("${spring.profiles.active}")
    private String code;
    @Value("${k8s.path}")
    private String k8Path;
    @SneakyThrows
    public ApiClient getApi() {
            //更改自己的k8s的yml地址  
            String path = K8sServiceController.class.getClassLoader().getResource("kubeconfig-108.yml").getPath();
            //加载k8s,confg
            ApiClient client = ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader(path))).build();
            System.out.println("*****************************************druid----------------------------------------************************");
            //将加载confi的client设置为默认的client
            Configuration.setDefaultApiClient(client);
            return client;
       
    }
}

1. 创建命名空间

 /**
     * 创建命名空间
     */
    @PostMapping("createNamespace")
    public R createNamespace(@RequestBody K8sEntity k8sEntity) throws IOException {
// 实体可以自己定义
        ApiClient client = k8sConfig.getApi();
        CoreV1Api api = new CoreV1Api(client);
         V1Namespace body = new V1Namespace();
        Boolean includeUninitialized = null;
        String pretty = null;
        String dryRun = null;
        body.setApiVersion("v1");
        body.setKind("Namespace");
        V1ObjectMeta metadata = new V1ObjectMeta();
        metadata.setName(k8sEntity.getNamespace());
        Map<String, String> labelMap = new HashMap<>();
        labelMap.put("app", "ccb");
        metadata.setLabels(labelMap);
        body.setMetadata(metadata);
        try {
            V1Namespace v1Namespace = api.createNamespace(body, includeUninitialized, pretty, dryRun);
        return R.ok();
    }

2.万能api 可以创建任何想创建的

 public void yyds(String name) throws ApiException {
        ApiClient client = k8sConfig.getApi();
// 自定义发送路径
        CustomObjectsApi customObjectsApi = new CustomObjectsApi(client);
        V1DeleteOptions deleteOptions = new V1DeleteOptions();
//        deleteOptions.setPropagationPolicy("Foreground");
//        /apis/kubeflow.org/v1/namespaces/{namespace}/tfjobs/{name}
        try {
// /api/{group}/{version}/namespaces/{namespace}/{plural}/{name} 一一对应
            Object response = customObjectsApi.deleteNamespacedCustomObject("kubeflow.org", "v1", "fz-" + SecurityUtils.getUserId(), "tfjobs", name, deleteOptions, 0, null, null);
            System.out.println("TFJob删除成功");
        } catch (ApiException e) {
            System.out.println("TFJob删除失败: " + e.getMessage());
        }
    }

原理:

在工具包最终发送请求时 是拼接路径  例 其中的删除CustomObject方法

源码: 我将重要方法重写  就能随心所遇的更改任何的路径  就不用考虑请求发送认证的关系(为了展示 这就是我没有改动)

 @Override
        public com.squareup.okhttp.Call deleteNamespacedCustomObjectCall(String group, String version, String namespace, String plural,
                                                                         String name, V1DeleteOptions body, Integer gracePeriodSeconds, Boolean orphanDependents,
                                                                         String propagationPolicy, final ProgressResponseBody.ProgressListener progressListener,
                                                                         final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
            Object localVarPostBody = body;

            // create path and map variables
            String localVarPath = "/api/{group}/{version}/namespaces/{namespace}/{plural}/{name}"
                    .replaceAll("\\{" + "group" + "\\}", super.getApiClient().escapeString(group.toString()))
                    .replaceAll("\\{" + "version" + "\\}", super.getApiClient().escapeString(version.toString()))
                    .replaceAll("\\{" + "namespace" + "\\}", super.getApiClient().escapeString(namespace.toString()))
                    .replaceAll("\\{" + "plural" + "\\}", super.getApiClient().escapeString(plural.toString()))
                    .replaceAll("\\{" + "name" + "\\}", super.getApiClient().escapeString(name.toString()));

            List<Pair> localVarQueryParams = new ArrayList<Pair>();
            List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
            if (gracePeriodSeconds != null)
                localVarQueryParams.addAll(super.getApiClient().parameterToPair("gracePeriodSeconds", gracePeriodSeconds));
            if (orphanDependents != null)
                localVarQueryParams.addAll(super.getApiClient().parameterToPair("orphanDependents", orphanDependents));
            if (propagationPolicy != null)
                localVarQueryParams.addAll(super.getApiClient().parameterToPair("propagationPolicy", propagationPolicy));

            Map<String, String> localVarHeaderParams = new HashMap<String, String>();

            Map<String, Object> localVarFormParams = new HashMap<String, Object>();

            final String[] localVarAccepts = {
                    "application/json"
            };
            final String localVarAccept = super.getApiClient().selectHeaderAccept(localVarAccepts);
            if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);

            final String[] localVarContentTypes = {
                    "*/*"
            };
            final String localVarContentType = super.getApiClient().selectHeaderContentType(localVarContentTypes);
            localVarHeaderParams.put("Content-Type", localVarContentType);

            if (progressListener != null) {
                super.getApiClient().getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
                    @Override
                    public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
                        com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
                        return originalResponse.newBuilder()
                                .body(new ProgressResponseBody(originalResponse.body(), progressListener))
                                .build();
                    }
                });
            }

            String[] localVarAuthNames = new String[]{"BearerToken"};
            return super.getApiClient().buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值