前言
使用kubernetes-client访问k8s apiserver,直接贴代码了
配置类ApiClientConfig(自己根据需要改)
package com.pdd.transports.config;
import com.yiran.arch.leo.client.ConfigCache;
import io.kubernetes.client.ApiClient;
import io.kubernetes.client.apis.AppsV1Api;
import io.kubernetes.client.apis.CoreV1Api;
import io.kubernetes.client.apis.ExtensionsV1beta1Api;
import io.kubernetes.client.apis.RbacAuthorizationV1Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
/**
* @author jinhaozhi
*/
@Slf4j
@Configuration
public class ApiClientConfig {
// 直接使用eden-api的配置
private static final String CONFIG_KEY = "eden-api.k8s.kube.config";
private static final String CONFIG_DEBUG_KEY = "eden-api.k8s.debug.switch";
@Value("${" + CONFIG_KEY + "}")
private String config;
@Value("${" + CONFIG_DEBUG_KEY + "}")
private String debug;
@Bean
@Primary
public ApiClient initK8sApiClient() {
try {
InputStream configStream = new ByteArrayInputStream(config.getBytes());
final ApiClient apiClient = io.kubernetes.client.util.Config.fromConfig(configStream);
apiClient.setDebugging(Boolean.valueOf(debug));
io.kubernetes.client.Configuration.setDefaultApiClient(apiClient);
ConfigCache.getInstance().addChange((key, value) -> {
if (CONFIG_KEY.equals(key)) {
log.warn("[ LEO ] Change k8s config, this change should have no effect.");
} else if (CONFIG_DEBUG_KEY.equals(key)) {
debug = value;
apiClient.setDebugging(Boolean.valueOf(value));
}