Kubernetes official java client four: internal applications

Welcome to my GitHub

https://github.com/zq2599/blog_demos
content: classification summary of all original articles and supporting source code, involving Java, Docker, Kubernetes, DevOPS, etc.;

Overview

  1. This article is the fourth in the "Kubernetes official java client" series. The java clients mentioned below refer to client-jar.jar;

  2. In the previous article "Kubernetes Official Java Client III: External Application" , we developed a SpringBoot application named OutsideclusterApplication . The application is not deployed in the K8S environment, but remotely accesses the API Server inside the K8S environment. The overall structure is as follows:
    Insert picture description here

  3. In addition to the external deployment method in the previous article, there is also a common scenario: the application using the java client itself is also deployed in the K8S environment, as shown in the following figure, the SpringBoot application named DemoApplication is deployed in the K8S environment and calls the java client library The API performs various operations on K8S, the overall structure is as follows:
    Insert picture description here

  4. The content of this article is to develop the application named DemoApplication in the above figure , and deploy it in the K8S environment for verification;

Extra preparation

  1. SpringBoot is made into a docker image, the official recommended method is preferred, refer to "Experiencing SpringBoot (2.3) Application Making Docker Image (Official Plan)" , "Detailed SpringBoot (2.3) Application Making Docker Image (Official Plan)"
  2. For the probe technology of SpringBoot application in the K8S environment, please refer to "Mastering SpringBoot-2.3 Container Probes: Basics" , "Mastering SpringBoot-2.3 Container Probes: In-depth Chapter" , "Mastering SpringBoot-2.3 Container Probes: Actual combat

Source download

  1. If you don't want to code, you can download all the source code on GitHub. The address and link information are shown in the following table (https://github.com/zq2599/blog_demos):
name link Remarks
Project homepage https://github.com/zq2599/blog_demos The project's homepage on GitHub
git warehouse address (https) https://github.com/zq2599/blog_demos.git The warehouse address of the project source code, https protocol
git warehouse address (ssh) [email protected]:zq2599/blog_demos.git The warehouse address of the source code of the project, ssh protocol
  1. There are multiple folders in this git project. The application of this chapter is under the kubernetesclient folder, as shown in the red box below:
    Insert picture description here

Develop applications in the K8S environment: DemoApplication

  1. Open the kubernetesclient project created in "Kubernetes Official Java Client: Preparation" , and create a subproject in it called helloworld . This is a SpringBoot project. The content of pom.xml is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.bolingcavalry</groupId>
        <artifactId>kubernetesclient</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <groupId>com.bolingcavalry</groupId>
    <artifactId>helloworld</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>helloworld</name>
    <description>Demo project for Spring Boot</description>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        
        <dependency>
            <groupId>io.kubernetes</groupId>
            <artifactId>client-java</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.0.RELEASE</version>
                <!--该配置会在jar中增加layer描述文件,以及提取layer的工具-->
                <configuration>
                    <layers>
                        <enabled>true</enabled>
                    </layers>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
  1. Write the java code and create DemoApplication.java . For the sake of simplicity, write the code of the boot class and web controller in the DemoApplication class:
package com.bolingcavalry.demo;

import com.google.gson.Gson;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1PodList;
import io.kubernetes.client.util.Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@SpringBootApplication
@RestController
@Slf4j
public class DemoApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(DemoApplication.class, args);
    }

    @RequestMapping(value = "/hello")
    public List<String> hello() throws Exception {
    
    
        ApiClient client = Config.defaultClient();
        Configuration.setDefaultApiClient(client);

        CoreV1Api api = new CoreV1Api();

        // 调用客户端API取得所有pod信息
        V1PodList v1PodList = api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);

        // 使用Gson将集合对象序列化成JSON,在日志中打印出来
        log.info("pod info \n{}", new Gson().toJson(v1PodList));

        return v1PodList
                .getItems()
                .stream()
                .map(value ->
                        value.getMetadata().getNamespace()
                        + ":"
                        + value.getMetadata().getName())
                .collect(Collectors.toList());
    }
}
  1. Remember the serialization issues mentioned in "Kubernetes Official Java Client Two: Serialization and Deserialization Issues" ? In the above code, in the log.info code, the serialization of V1PodList is Gson, and the hello method returns not a V1PodList instance, but a new List instance. This is because jackson serializes V1PodList. Cause an exception, here to avoid jackson participating in the serialization operation;
  2. The application code has been written, and the next step is the Dockerfile file used for mirroring. This file and the pom.xml file just created are in the same directory (that is, the subproject helloworld folder). The content of the Dockerfile is as follows:
# 指定基础镜像,这是分阶段构建的前期阶段
FROM openjdk:8u212-jdk-stretch as builder
# 执行工作目录
WORKDIR application
# 配置参数
ARG JAR_FILE=target/*.jar
# 将编译构建得到的jar文件复制到镜像空间中
COPY ${JAR_FILE} application.jar
# 通过工具spring-boot-jarmode-layertools从application.jar中提取拆分后的构建结果
RUN java -Djarmode=layertools -jar application.jar extract

# 正式构建镜像
FROM openjdk:8u212-jdk-stretch
WORKDIR application
# 前一阶段从jar中提取除了多个文件,这里分别执行COPY命令复制到镜像空间中,每次COPY都是一个layer
COPY --from=builder application/dependencies/ ./
COPY --from=builder application/spring-boot-loader/ ./
COPY --from=builder application/snapshot-dependencies/ ./
COPY --from=builder application/application/ ./
ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"]
  1. Execute the following command in the directory where the pom.xml file of the subproject is located to complete the compilation and construction:
mvn clean package -U -DskipTests
  1. The next step is to make the image file. Please make sure that docker is installed and running on the current computer. In addition, the operation of building the docker image can only be executed successfully under macOS and Linux operating systems. If it is successful in the Windows environment, please try it yourself;
  2. Execute the following command in the directory where the Dockerfile is located to create a docker image file:
docker build -t 192.168.50.43:5888/common/helloworld:1.0-SNAPSHOT .
  1. After the above command is successfully executed, the image file is only in the docker warehouse of the machine. Please place it where the K8S environment can access. Here I have deployed the image warehouse Harbor on the intranet, and execute the following command to push it from the local warehouse Harbor (may need to log in first, related to Harbor settings):
    Insert picture description here

  2. The image preparation is complete, the next step is to deploy in the K8S environment, create a file named helloworld.yaml in the K8S environment, the content is as follows, it can be seen that the deployment and service are configured, and please note that the value of the serviceAccountName attribute is kubernates-client-service -account, this serviceAccountName is an RBAC resource created in the article " One of the Official Kubernetes Java Clients: Preparation" , so that the helloworld application we developed has permission to request API Server:

apiVersion: v1
kind: Service
metadata:
  name: helloworld
  namespace : kubernetesclient
spec:
  type: NodePort
  ports:
    - port: 8080
      nodePort: 30100
  selector:
    name: helloworld
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  namespace : kubernetesclient
  name: helloworld
spec:
  replicas: 1
  template:
    metadata:
      labels:
        name: helloworld
    spec:
      serviceAccountName: kubernates-client-service-account
      containers:
        - name: helloworld
          image: 192.168.50.43:5888/common/helloworld:1.0-SNAPSHOT
          tty: true
          livenessProbe:
            httpGet:
              path: /actuator/health/liveness
              port: 8080
            initialDelaySeconds: 5
            failureThreshold: 10
            timeoutSeconds: 10
            periodSeconds: 5
          readinessProbe:
            httpGet:
              path: /actuator/health/readiness
              port: 8080
            initialDelaySeconds: 5
            timeoutSeconds: 10
            periodSeconds: 5
          ports:
            - containerPort: 8080
          resources:
            requests:
              memory: "512Mi"
              cpu: "100m"
            limits:
              memory: "1Gi"
              cpu: "1000m"
  1. Execute the command in the directory where helloworld.yaml is located: kubectl apply -f helloworld.yaml
    Insert picture description here

  2. On my side, the IP address of the host where the Pod in the above picture is located is 192.168.50.135 , so use a browser to visit http://192.168.50.135:30100/hello , as shown in the figure below, it can be seen that all Pod names in the current K8S environment are returned :
    Insert picture description here

At this point, the SpringBoot application has successfully obtained information about the K8S environment where it is located through the K8S official java client. Through the previous article and this chapter, we have a basic understanding of the K8S official java client. The next actual combat will open this client. Abundant ability

Guess you like

Origin blog.csdn.net/boling_cavalry/article/details/107552495