1、pom.xml

   <!-- k8s client --><dependency><groupId>io.kubernetes</groupId><artifactId>client-java</artifactId><version>12.0.1</version></dependency>

2、把k8s-confg配置放在项目的resource/k8s下

~/.kube/config

3、k8s服务器配置token

kubectl config view -o jsonpath='{"Cluster name\tServer\n"}{range .clusters[*]}{.name}{"\t"}{.cluster.server}{"\n"}{end}'
export CLUSTER_NAME="kubernetes"
APISERVER=$(kubectl config view -o jsonpath="{.clusters[?(@.name==\"$CLUSTER_NAME\")].cluster.server}")TOKEN=$(kubectl get secrets -o jsonpath="{.items[?(@.metadata.annotations['kubernetes\.io/service-account\.name']=='default')].data.token}"|base64 -d)curl -X GET $APISERVER/api --header "Authorization: Bearer $TOKEN" --insecure

成功如下:

echo $TOKEN

4、把这个token配置到java项目中

5、k8s 连接工具类


import com.example.modelmanager.exception.BizException;
import io.kubernetes.client.custom.IntOrString;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.apis.ExtensionsV1beta1Api;
import io.kubernetes.client.openapi.apis.NetworkingV1Api;
import io.kubernetes.client.openapi.auth.ApiKeyAuth;
import io.kubernetes.client.openapi.models.*;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.KubeConfig;
import io.kubernetes.client.util.Yaml;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Map;@Slf4j
@Component
public class K8sHandleTools {@Value("${k8s.token}")private String k8sToken;/** 加载yaml配置文件** @param path* @throws IOException*/public static Object loadYaml(String path) throws IOException {Reader reader = new FileReader(path);return Yaml.load(reader);}public  ApiClient getApiClient(String k8sConfig) {try {String kubeConfigPath = ResourceUtils.getURL(k8sConfig).getPath();ApiClient client =ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))).build();
//            Configuration.setDefaultApiClient(client);
//            ApiClient defaultClient = Configuration.getDefaultApiClient();
//            ApiKeyAuth BearerToken = (ApiKeyAuth) defaultClient.getAuthentication("BearerToken");ApiKeyAuth BearerToken = (ApiKeyAuth) client.getAuthentications().get("BearerToken");BearerToken.setApiKey(k8sToken);return client;} catch (IOException e) {log.error("读取kubeConfigPath异常", e);throw new BizException("500","读取kubeConfigPath异常");} catch (Exception e) {log.error("构建K8s-Client异常", e);throw new BizException("500","构建K8s-Client异常");}}public V1Pod deletePod(ApiClient apiClient, String namespace, String podName) {// new a CoreV1ApiCoreV1Api api = new CoreV1Api(apiClient);// invokes the CoreV1Api clienttry {return api.deleteNamespacedPod(podName,namespace,null,null,null,null,null,null);} catch (ApiException e) {log.error("deletePod 异常:" + e.getResponseBody(), e);throw new BizException("500", e.getMessage());}}public V1PodList getNamesapcePod(ApiClient apiClient, String namespace) {// new a CoreV1ApiCoreV1Api api = new CoreV1Api(apiClient);// invokes the CoreV1Api clienttry {return api.listNamespacedPod(namespace,null,null, null,null,null,null,null,null,null,null);} catch (ApiException e) {log.error("获取 NamesapcePod 异常:" + e.getResponseBody(), e);throw new BizException("500", e.getMessage());}}/*** 获取所有的Pod** @return podList*/public V1PodList getAllPodList(ApiClient apiClient) {// new a CoreV1ApiCoreV1Api api = new CoreV1Api(apiClient);// invokes the CoreV1Api clienttry {return api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null, null);} catch (ApiException e) {log.error("获取podlist异常:" + e.getResponseBody(), e);throw new BizException("500", e.getMessage());}}/*** 创建k8s service** @param namespace   命名空间* @param serviceName 服务名称* @param port        服务端口号(和目标pod的端口号一致)* @param selector    pod标签选择器* @return 创建成功的service对象*/public V1Service createService(ApiClient apiClient, String namespace, String serviceName, Integer port, Map<String, String> selector) {//构建service的yaml对象V1Service svc = new V1ServiceBuilder().withNewMetadata().withName(serviceName).endMetadata().withNewSpec().addNewPort().withProtocol("TCP").withPort(port).withTargetPort(new IntOrString(port)).endPort().withSelector(selector).endSpec().build();// Deployment and StatefulSet is defined in apps/v1, so you should use AppsV1Api instead of CoreV1APICoreV1Api api = new CoreV1Api(apiClient);V1Service v1Service = null;try {v1Service = api.createNamespacedService(namespace, svc, null, null, null);} catch (ApiException e) {log.error("创建service异常:" + e.getResponseBody(), e);throw new BizException("500", e.getMessage());} catch (Exception e) {log.error("创建service系统异常:", e);throw new BizException("500", e.getMessage());}return v1Service;}/*** 创建k8s V1Ingress** @param namespace   命名空间* @param ingressName ingress名称* @param annotations ingress注解* @param path        匹配的路径* @param serviceName 路由到的服务名称* @param servicePort 路由到的服务端口* @return 创建成功的ingress对象*/public V1Ingress createV1Ingress(ApiClient apiClient, String namespace, String ingressName, Map<String, String> annotations, String path,String serviceName, Integer servicePort) {//构建ingress的yaml对象V1Ingress ingress = new V1IngressBuilder().withNewMetadata().withName(ingressName).withAnnotations(annotations).endMetadata().withNewSpec().addNewRule().withHttp(new V1HTTPIngressRuleValueBuilder().addToPaths(new V1HTTPIngressPathBuilder().withPath(path).withPathType("Prefix").withBackend(new V1IngressBackendBuilder().withService(new V1IngressServiceBackendBuilder().withName(serviceName).withPort(new V1ServiceBackendPortBuilder().withNumber(servicePort).build()).build()).build()).build()).build()).endRule().endSpec().build();//调用对应的API执行创建ingress的操作NetworkingV1Api api = new NetworkingV1Api(apiClient);V1Ingress v1Ingress = null;try {v1Ingress = api.createNamespacedIngress(namespace, ingress, null, null, null);} catch (ApiException e) {log.error("创建ingress异常:" + e.getResponseBody(), e);throw new BizException("500", e.getMessage());} catch (Exception e) {log.error("创建ingress系统异常:", e);throw new BizException("500", e.getMessage());}return v1Ingress;}/*** 创建k8s ExtensionIngress** @param namespace   命名空间* @param ingressName ingress名称* @param annotations ingress注解* @param path        匹配的路径* @param serviceName 路由到的服务名称* @param servicePort 路由到的服务端口* @return 创建成功的ingress对象*/public ExtensionsV1beta1Ingress createExtensionIngress(ApiClient apiClient, String namespace, String ingressName, Map<String, String> annotations, String path,String serviceName, Integer servicePort) {//构建ingress的yaml对象ExtensionsV1beta1Ingress ingress = new ExtensionsV1beta1IngressBuilder().withNewMetadata().withName(ingressName).withAnnotations(annotations).endMetadata().withNewSpec().addNewRule().withHttp(new ExtensionsV1beta1HTTPIngressRuleValueBuilder().addToPaths(new ExtensionsV1beta1HTTPIngressPathBuilder().withPath(path).withBackend(new ExtensionsV1beta1IngressBackendBuilder().withServiceName(serviceName).withServicePort(new IntOrString(servicePort)).build()).build()).build()).endRule().endSpec().build();//调用对应的API执行创建ingress的操作ExtensionsV1beta1Api api = new ExtensionsV1beta1Api(apiClient);ExtensionsV1beta1Ingress extensionsV1beta1Ingress = null;try {extensionsV1beta1Ingress = api.createNamespacedIngress(namespace, ingress, null, null, null);} catch (ApiException e) {log.error("创建ingress异常:" + e.getResponseBody(), e);throw new BizException("500", e.getMessage());} catch (Exception e) {log.error("创建ingress系统异常:", e);throw new BizException("500", e.getMessage());}return extensionsV1beta1Ingress;}
}

6、连接测试

@RestController
@Api(tags = "引擎管理接口")
@RequestMapping("/engine")
@Slf4j
public class EngineController {@ApiOperation("引擎连接接口")@PostMapping("/k8s")public ResultBody connectK8s(String namespace, String podName){V1PodList v1PodList =  k8sHandleTools.getNamesapcePod(k8sHandleTools.getApiClient(k8sConfig),"default");for(V1Pod v1Pod: v1PodList.getItems()){log.info(v1Pod.toString());}return ResultBody.success("connect k8s success");}
}

使用 java-client 连接k8s相关推荐

  1. Paho Java Client 连接阿里云物联网平台

    Paho Java Client 连接阿里云物联网平台 进入阿里云物联网平台->点击产品->新建 点击设备->添加设备 查看设备证书,复制记录,后面使用 阿里云TCP通信 一机一密. ...

  2. TDH Kerberos java client 连接Hyperbase(Hbase)

    TDH Kerberos java client 连接Hyperbase(Hbase) 异常信息 SASL authentication failed. The most likely cause i ...

  3. java http连接es_连接es

    web端连接es java client 连接es遇到的2个问题 没有可用的节点 javaclient连接未经配置的es,会报出None of the configured nodes are ava ...

  4. java jdbc 连接ignite_Apache Ignite 学习笔记(二): Ignite Java Thin Client

    前一篇文章,我们介绍了如何安装部署Ignite集群,并且尝试了用REST和SQL客户端连接集群进行了缓存和数据库的操作.现在我们就来写点代码,用Ignite的Java thin client来连接集群 ...

  5. [Kerberos] Java client访问kerberos-secured cluster

    使用java client访问kerberos-secured cluster,最重要的是先从admin那里拿到可用的keytab文件,用来作认证.接下来就是调整连接的配置.以下先用连接hdfs为例进 ...

  6. mq 接口 java_Rabbitmq Java Client Api详解

    AMQP AMQP协议是一个高级抽象层消息通信协议,RabbitMQ是AMQP协议的实现. 基础概念快速入门 每个rabbitmq-server叫做一个Broker,等着tcp连接进入. 在rabbi ...

  7. (RabbitMQ) Java Client API Guide

    欢迎支持笔者新作:<深入理解Kafka:核心设计与实践原理>和<RabbitMQ实战指南>,同时欢迎关注笔者的微信公众号:朱小厮的博客. 本篇翻译的是RabbitMQ官方文档关 ...

  8. Java hdfs连接池_Java使用连接池管理Hdfs连接

    记录一下Java API 连接hadoop操作hdfs的实现流程(使用连接池管理). 以前做过这方面的开发,本来以为不会有什么问题,但是做的还是坑坑巴巴,内心有些懊恼,记录下这烦人的过程,警示自己切莫 ...

  9. 译:1. RabbitMQ Java Client 之 Hello World

    这些教程介绍了使用RabbitMQ创建消息传递应用程序的基础知识.您需要安装RabbitMQ服务器才能完成教程 1. 打造第一个Hello World 程序 RabbitMQ是一个消息代理:它接受和转 ...

  10. java client和servers_“java -server”和“java -client”之间的真正区别?

    这实际上与HotSpot和默认选项值 ( Java HotSpot VM选项 )相关联,这些选项在客户端和服务器configuration之间有所不同. 从白皮书( The Java HotSpot ...

最新文章

  1. ​赠书:面向对象的两大迷思,再给你们解答一次
  2. [python学习] 专题九.Mysql数据库编程基础知识
  3. web开发:jquery之DOM
  4. 蓝桥杯第七届国赛JAVA真题----机器人塔
  5. Windows下使用emacs+cscope
  6. django+uwsgi+nginx部署
  7. 贪吃蛇速度变快c语言程序,简单贪吃蛇C语言程序
  8. Tensorflow2.0---SSD网络原理及代码解析(一)
  9. c语言实验上机报告,c语言上机实验报告_实验报告.doc
  10. python描述对象静态特性的数据为_对于需要几个单位共同负担的一张原始凭证上的支出,应根据其他单位负担部分为其提高( )。...
  11. ionic2入门教程(三)高仿网易公开课(1)
  12. elk笔记20--Analysis
  13. 苹果手机软件升级密码_苹果app应用制作多少钱_广腾(深圳)互联网科技有限公司...
  14. 手把手教你应用三种工厂模式在SpringIOC中创建对象实例【案例详解】
  15. Android开发项目——智能农业(知识点整理回顾)
  16. cyclic查看缓冲区溢出长度
  17. 微信号复制跟跳转——clipboard.js
  18. 阿里巴巴之孕育、裂变及归因
  19. Java多线程-Thread、Runnable、Executor
  20. Python语句结构(控制语句)

热门文章

  1. (程序员内在修炼)《熔炉》观后感:承认并且面对生活的丑陋面
  2. ME4012磁盘服务器更换硬盘
  3. python画旺仔代码_简笔画教程:教你画旺仔
  4. 前端工程师,还在学习那些永无止尽的框架么?
  5. Qt仿QQ截图之QTextEdit宽高自适应
  6. matplotlib 绘图
  7. Ubuntu20.04静态IP设置
  8. Java instanceof用法详解
  9. 15.方法引用, Stream流,File类 , 递归 ,字节流
  10. 思科考试注册流程详解----VUE考点现场演示-晁海江-专题视频课程