如果操作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);
}
}