

依赖准备
核心依赖
<dependency>
<groupId>io.fabric8</groupId>
<artifactId>kubernetes-client</artifactId>
<version>4.12.0</version>
</dependency>
辅助依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
代码演示及分析
客户端的创建
Kubernetes 的资源默认是对内部是可见并可以访问的,我们可以通过以下方式去访问Kubernetes 获取我们想要的资源。
1.对于Kubernetes 可以使用 JavaAPI 通过安全证书文件、Token或admin.conf配置外部访问
2.同样也可以配置这些配置文件通过HTTP访问apiService访问
3.内部也可以通过kube-proxy将内部数据暴露出来进行访问的方式。
通过安全证书访问
需要安全证书文件:apiserver-kubelet-client.crt、apiserver-kubelet-client.key、ca.crt
//创建 Config 用于创建 Client Config config = new ConfigBuilder() .withMasterUrl("ip") .withCaCertData("ca.crt内容") .withClientCertData("apiserver-kubelet-client.crt内容") .withClientKeyData("apiserver-kubelet-client.key内容") .build(); // 创建Client KubernetesClient kubernetesClient = new DefaultKubernetesClient(config); |
通过配置文件访问
需要配置文件:admin.conf
Config config = Config.fromKubeconfig("admin.conf内容"); KubernetesClient kubernetesClient = new DefaultKubernetesClient(config); |
kube-proxy 配置后通过 HTTP 直接访问
首先在服务器中开启kube-proxy代理暴露8080端口:nohup kubectl proxy --port=8080 &
public void main(String[] args) throws IOException {
Config config = new ConfigBuilder().withMasterUrl("http://127.0.0.1:8080").build(); KubernetesClient kubernetesClient = new DefaultKubernetesClient(config); //通过http访问k8s中的路径资源 HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet("http://127.0.0.1:8080/apis/devices.kubeedge.io/v1alpha1/devices"); HttpResponse response = null; response = httpClient.execute(httpGet); HttpEntity responseEntity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); int code = statusLine.getStatusCode(); String result = EntityUtils.toString(responseEntity); } |
http浏览器直接访问K8S资源
安装证书
访问操作pod、node等基础资源
public static void main(String[] args) {
KubernetesClient client = null; //查看Pod MixedOperation<Pod, PodList, DoneablePod, PodResource<Pod, DoneablePod>> operation = client.pods(); //创建Pod,获取资源处理类,在传入组装号的Pod类 NonNamespaceOperation pods = client.pods().inNamespace("default"); //配置Pod,还可以通过 pod 类组装,想要运行 这里的参数是不够的,仅作演示 Pod pod1 = new PodBuilder().withNewMetadata().withName("pod1").withNamespace("default").and().build(); pods.create(pod1); //删除同上 pods.delete(pod1); } |
访问操作复杂管理器Deployment控制器
封装资源组装
public class K8sDeploymentConf {
/** * 用于组合 Deploymen * @param appName * @param image * @param nodeName * @return */ public static Deployment getDepandDeployment(String appName, String image, String nodeName) {
//参数传递 String appGroup = "appGroup"; //参数 Map<String, String> labels = new HashMap<String, String>(); labels.put("app", appGroup); Map<String, String> nodeSelector = new HashMap<String, String>(); nodeSelector.put("name", nodeName); //mataData 数据组装 ObjectMeta mataData = new ObjectMeta(); mataData.setName(appName); mataData.setLabels(labels); //镜像设置 Container container = new Container(); container.setName(appName); container.setImage(image); container.setImagePullPolicy("IfNotPresent"); SecurityContext sc = new SecurityContext(); sc.setPrivileged(true); container.setSecurityContext(sc); List<Container> containers = new ArrayList<>(); containers.add(container); //Spec 数据组装 //1.selector LabelSelector ls = new LabelSelector(); ls.setMatchLabels(labels); //2.template ObjectMeta empMataData = new ObjectMeta(); empMataData.setLabels(labels); PodSpec pods = new PodSpec(); pods.setHostNetwork(true); pods.setNodeSelector(nodeSelector); pods.setContainers(containers); //2.2 组装 PodTemplateSpec pt = new PodTemplateSpec(); pt.setMetadata(empMataData); pt.setSpec(pods); //3.spec 组合 DeploymentSpec ds = new DeploymentSpec(); ds.setReplicas(1); ds.setSelector(ls); ds.setTemplate(pt); //Deployment 设置 Deployment deployment = new Deployment(); deployment.setApiVersion("apps/v1"); deployment.setKind("Deployment"); deployment.setMetadata(mataData); deployment.setSpec(ds); return deployment; }
} |
Deployment操作
public static void main(String[] args) {
KubernetesClient client = null; //查看Pod MixedOperation<Pod, PodList, DoneablePod, PodResource<Pod, DoneablePod>> operation = client.pods(); //创建Pod,获取资源处理类,在传入组装号的Pod类 NonNamespaceOperation pods = client.pods().inNamespace("default"); //配置Pod,还可以通过 pod 类组装,想要运行 这里的参数是不够的,仅作演示 Pod pod1 = new PodBuilder().withNewMetadata().withName("pod1").withNamespace("default").and().build(); pods.create(pod1); //删除同上 pods.delete(pod1); } |
RestTemplate
若果是完全采用SpringBoot开发,可以基于RestTemplate调用K8S的API操作
RestTemplate只是对其他的HTTP客户端的封装,其本身并没有实现HTTP相关的基础功能。其底层实现是可以配置切换的
默认 RestTemplate进行http相关的请求的最底层的实现是利用的java原生的api java.net.URLConnection等实现的

原生JDK中的http请求处理
/** * java 原生http请求 */ public class NativeHttp {
public static void main(String[] args) {
postDemo(); }
/** * POST请求 */ public static void postDemo() {
try {
// 请求的地址 String spec = "http://localhost:8080/test022"; // 根据地址创建URL对象 URL url = new URL(spec); // 根据URL对象打开链接 HttpURLConnection urlConnection = (HttpURLConnection) url .openConnection(); // 设置请求方法 urlConnection.setRequestMethod("POST"); // 设置请求的超时时间 urlConnection.setReadTimeout(5000); urlConnection.setConnectTimeout(5000); // 传递的数据 String data = "name=" + URLEncoder.encode("aaa", "UTF-8") + "&school=" + URLEncoder.encode("bbbb", "UTF-8"); // 设置请求的头 urlConnection.setRequestProperty("Connection", "keep-alive"); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded" |