https://github.com/zq2599/blog_demoshtml
內容:全部原創文章分類彙總及配套源碼,涉及Java、Docker、Kubernetes、DevOPS等;java
這是篇萬字長文,因此一開始就要明確本文的核心內容:開發一個SpringBoot應用並部署在kubernetes環境,這個應用經過kubernetes的java客戶端向API Server發請求,請求內容包括:建立名爲test123的deployment、對這個deployment進行patch操做,以下圖:node
接下來先了解一些kubernetes的patch相關的基本知識;nginx
kubernetes的patch一共有四種:git
名稱 | 連接 | 備註 |
---|---|---|
項目主頁 | https://github.com/zq2599/blog_demos | 該項目在GitHub上的主頁 |
git倉庫地址(https) | https://github.com/zq2599/blog_demos.git | 該項目源碼的倉庫地址,https協議 |
git倉庫地址(ssh) | git@github.com:zq2599/blog_demos.git | 該項目源碼的倉庫地址,ssh協議 |
準備工做包括建立工程、編寫輔助功能代碼、初始化代碼等:程序員
<?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>patch</artifactId> <version>0.0.1-SNAPSHOT</version> <name>patch</name> <description>patch demo</description> <packaging>jar</packaging> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-json</artifactId> </exclusion> </exclusions> </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>
package com.bolingcavalry.patch; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.stream.Collectors; import org.springframework.core.io.ClassPathResource; public class ClassPathResourceReader { private final String path; private String content; public ClassPathResourceReader(String path) { this.path = path; } public String getContent() { if (content == null) { try { ClassPathResource resource = new ClassPathResource(path); BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream())); content = reader.lines().collect(Collectors.joining("\n")); reader.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } return content; } }
public static void main(String[] args) { SpringApplication.run(PatchExample.class, args); }
static String DEPLOYMENT_NAME = "test123"; static String NAMESPACE = "default";
static String deployStr, jsonStr, mergeStr, strategicStr, applyYamlStr;
@PostConstruct private void init() throws IOException { // 設置api配置 ApiClient client = Config.defaultClient(); Configuration.setDefaultApiClient(client); // 設置超時時間 Configuration.getDefaultApiClient().setConnectTimeout(30000); // 部署用的JSON字符串 deployStr = new ClassPathResourceReader("deploy.json").getContent(); // json patch用的JSON字符串 jsonStr = new ClassPathResourceReader("json.json").getContent(); // merge patch用的JSON字符串,和部署的JSON相比:replicas從1變成2,增長一個名爲from的label,值爲merge mergeStr = new ClassPathResourceReader("merge.json").getContent(); // strategic merge patch用的JSON字符串 strategicStr = new ClassPathResourceReader("strategic.json").getContent(); // server side apply用的JSON字符串 applyYamlStr = new ClassPathResourceReader("applyYaml.json").getContent(); }
/** * 通用patch方法 * @param patchFormat patch類型,一共有四種 * @param deploymentName deployment的名稱 * @param namespace namespace名稱 * @param jsonStr patch的json內容 * @param fieldManager server side apply用到 * @param force server side apply要設置爲true * @return patch結果對象轉成的字符串 * @throws Exception */ private String patch(String patchFormat, String deploymentName, String namespace, String jsonStr, String fieldManager, Boolean force) throws Exception { // 建立api對象,指定格式是patchFormat ApiClient patchClient = ClientBuilder .standard() .setOverridePatchFormat(patchFormat) .build(); log.info("start deploy : " + patchFormat); // 開啓debug便於調試,生產環境慎用!!! patchClient.setDebugging(true); // 建立deployment ExtensionsV1beta1Deployment deployment = new ExtensionsV1beta1Api(patchClient) .patchNamespacedDeployment( deploymentName, namespace, new V1Patch(jsonStr), null, null, fieldManager, force ); log.info("end deploy : " + patchFormat); return new GsonBuilder().setPrettyPrinting().create().toJson(deployment); }
{ "kind":"Deployment", "apiVersion":"extensions/v1beta1", "metadata":{ "name":"test123", "labels":{ "run":"test123" } }, "spec":{ "replicas":1, "selector":{ "matchLabels":{ "run":"test123" } }, "template":{ "metadata":{ "creationTimestamp":null, "labels":{ "run":"test123" } }, "spec":{ "terminationGracePeriodSeconds":30, "containers":[ { "name":"test123", "image":"nginx:1.18.0", "ports":[ { "containerPort":80 } ], "resources":{ } } ] } }, "strategy":{ } }, "status":{ } }
/** * 通用patch方法 * @param patchFormat patch類型,一共有四種 * @param deploymentName deployment的名稱 * @param namespace namespace名稱 * @param jsonStr patch的json內容 * @param fieldManager server side apply用到 * @param force server side apply要設置爲true * @return patch結果對象轉成的字符串 * @throws Exception */ private String patch(String patchFormat, String deploymentName, String namespace, String jsonStr, String fieldManager, Boolean force) throws Exception { // 建立api對象,指定格式是patchFormat ApiClient patchClient = ClientBuilder .standard() .setOverridePatchFormat(patchFormat) .build(); log.info("start deploy : " + patchFormat); // 開啓debug便於調試,生產環境慎用!!! patchClient.setDebugging(true); // 建立deployment ExtensionsV1beta1Deployment deployment = new ExtensionsV1beta1Api(patchClient) .patchNamespacedDeployment( deploymentName, namespace, new V1Patch(jsonStr), null, null, fieldManager, force ); log.info("end deploy : " + patchFormat); return new GsonBuilder().setPrettyPrinting().create().toJson(deployment); }
/** * 通用patch方法,fieldManager和force都默認爲空 * @param patchFormat patch類型,一共有四種 * @param jsonStr patch的json內容 * @return patch結果對象轉成的字符串 * @throws Exception */ private String patch(String patchFormat, String jsonStr) throws Exception { return patch(patchFormat, DEPLOYMENT_NAME, NAMESPACE, jsonStr, null, null); }
[ { "op":"replace", "path":"/spec/template/spec/terminationGracePeriodSeconds", "value":27 } ]
/** * JSON patch格式的關係 * * @return * @throws Exception */ @RequestMapping(value = "/patch/json", method = RequestMethod.GET) public String json() throws Exception { return patch(V1Patch.PATCH_FORMAT_JSON_PATCH, jsonStr); }
@RequestMapping(value = "/patch/fullmerge", method = RequestMethod.GET) public String fullmerge() throws Exception { return patch(V1Patch.PATCH_FORMAT_JSON_MERGE_PATCH, mergeStr); }
{ "spec":{ "template":{ "spec":{ "containers":[ { "name":"test456", "image":"tomcat:7.0.105-jdk8" } ] } } } }
@RequestMapping(value = "/patch/partmerge", method = RequestMethod.GET) public String partmerge() throws Exception { return patch(V1Patch.PATCH_FORMAT_JSON_MERGE_PATCH, strategicStr); }
@RequestMapping(value = "/patch/strategic", method = RequestMethod.GET) public String strategic() throws Exception { return patch(V1Patch.PATCH_FORMAT_STRATEGIC_MERGE_PATCH, strategicStr); }
@RequestMapping(value = "/patch/apply", method = RequestMethod.GET) public String apply() throws Exception { return patch(V1Patch.PATCH_FORMAT_APPLY_YAML, DEPLOYMENT_NAME, NAMESPACE, applyYamlStr, "example-field-manager", true); }
mvn clean package -U -DskipTests
# 指定基礎鏡像,這是分階段構建的前期階段 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"]
docker build -t 192.168.50.43:5888/common/patch:1.0-SNAPSHOT .
docker push 192.168.50.43:5888/common/patch:1.0-SNAPSHOT
apiVersion: v1 kind: Service metadata: name: patch namespace : kubernetesclient spec: type: NodePort ports: - port: 8080 nodePort: 30102 selector: name: patch --- apiVersion: extensions/v1beta1 kind: Deployment metadata: namespace : kubernetesclient name: patch spec: replicas: 1 template: metadata: labels: name: patch spec: serviceAccountName: kubernates-client-service-account containers: - name: patch image: 192.168.50.43:5888/common/patch: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"
kubectl apply -f patch.yaml
apiVersion: v1 kind: Service metadata: name: test123 namespace : default spec: type: NodePort ports: - port: 80 nodePort: 30101 selector: run: test123
kubectl apply -f nginx-service.yaml
先說一下驗證的步驟:github
merge patch(全量)給原有的deployment增長了一個label,先看看執行patch以前是啥樣,以下圖紅框:
web
瀏覽器訪問http://192.168.50.135:30102/patch/fullmerge ,就發起了merge請求,操做成功後再次查看,以下圖紅框,新增了一個label:redis
kubernetes的官方文檔中,提到此特性在低版本能夠經過開關來開啓,文檔地址:https://kubernetes.cn/docs/reference/command-line-tools-reference/feature-gates/
spring
我這裏kubernetes版本是1.14,所以須要手動開啓Server-side Apply,首先SSH登陸kubernetes環境;
打開文件/etc/kubernetes/manifests/kube-apiserver.yaml ,給spec.containers.command增長一個參數--feature-gates=ServerSideApply=true,以下圖紅框所示:
4. 用瀏覽器訪問test123提供的nginx服務,以下圖紅框所示,nginx版本已經升級,證實本次patch已經生效:
至此,經過kubernetes的java客戶端執行patch操做的實戰就所有完成了,從理論到環境準備,再到實際操做,涉及到太多內容,感謝您的耐心,但願本文能助您用好java客戶端這個利器,更高效的操做kubernetes環境;
微信搜索「程序員欣宸」,我是欣宸,期待與您一同暢遊Java世界...
https://github.com/zq2599/blog_demos