Spring Boot + k8s = 王炸!

来源:https://www.cnblogs.com/javastack/archive/2023/08/07/17610668.html
-Advertisement-
Play Games

來源:https://blog.csdn.net/qq_14999375/article/details/123309636 ## **前言** K8s + Spring Boot實現零宕機發佈:健康檢查+滾動更新+優雅停機+彈性伸縮+Prometheus監控+配置分離(鏡像復用) ## **配置* ...


來源:https://blog.csdn.net/qq_14999375/article/details/123309636

前言

K8s + Spring Boot實現零宕機發佈:健康檢查+滾動更新+優雅停機+彈性伸縮+Prometheus監控+配置分離(鏡像復用)

配置

健康檢查

  • 健康檢查類型:就緒探針(readiness)+ 存活探針(liveness)
  • 探針類型:exec(進入容器執行腳本)、tcpSocket(探測埠)、httpGet(調用介面)
業務層面

Spring Boot 基礎就不介紹了,推薦看這個實戰項目:

https://github.com/javastacks/spring-boot-best-practice

項目依賴 pom.xml

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

定義訪問埠、路徑及許可權 application.yaml

management:
  server:
    port: 50000                         # 啟用獨立運維埠
  endpoint:                             # 開啟health端點
    health:
      probes:
        enabled: true
  endpoints:
    web:
      exposure:
        base-path: /actuator            # 指定上下文路徑,啟用相應端點
        include: health

將暴露/actuator/health/readiness/actuator/health/liveness兩個介面,訪問方式如下:

http://127.0.0.1:50000/actuator/health/readiness
http://127.0.0.1:50000/actuator/health/liveness
運維層面

k8s部署模版deployment.yaml

apiVersion: apps/v1
kind: Deployment
spec:
  template:
    spec:
      containers:
      - name: {APP_NAME}
        image: {IMAGE_URL}
        imagePullPolicy: Always
        ports:
        - containerPort: {APP_PORT}
        - name: management-port
          containerPort: 50000         # 應用管理埠
        readinessProbe:                # 就緒探針
          httpGet:
            path: /actuator/health/readiness
            port: management-port
          initialDelaySeconds: 30      # 延遲載入時間
          periodSeconds: 10            # 重試時間間隔
          timeoutSeconds: 1            # 超時時間設置
          successThreshold: 1          # 健康閾值
          failureThreshold: 6          # 不健康閾值
        livenessProbe:                 # 存活探針
          httpGet:
            path: /actuator/health/liveness
            port: management-port
          initialDelaySeconds: 30      # 延遲載入時間
          periodSeconds: 10            # 重試時間間隔
          timeoutSeconds: 1            # 超時時間設置
          successThreshold: 1          # 健康閾值
          failureThreshold: 6          # 不健康閾值

滾動更新

k8s資源調度之滾動更新策略,若要實現零宕機發佈,需支持健康檢查

apiVersion: apps/v1
kind: Deployment
metadata:
  name: {APP_NAME}
  labels:
    app: {APP_NAME}
spec:
  selector:
    matchLabels:
      app: {APP_NAME}
  replicas: {REPLICAS}    # Pod副本數
  strategy:
    type: RollingUpdate    # 滾動更新策略
    rollingUpdate:
      maxSurge: 1                   # 升級過程中最多可以比原先設置的副本數多出的數量
      maxUnavailable: 1             # 升級過程中最多有多少個POD處於無法提供服務的狀態
優雅停機

在K8s中,當我們實現滾動升級之前,務必要實現應用級別的優雅停機。否則滾動升級時,還是會影響到業務。使應用關閉線程、釋放連接資源後再停止服務

業務層面

項目依賴 pom.xml

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

定義訪問埠、路徑及許可權 application.yaml

spring:
  application:
    name: <xxx>
  profiles:
    active: @profileActive@
  lifecycle:
    timeout-per-shutdown-phase: 30s     # 停機過程超時時長設置30s,超過30s,直接停機

server:
  port: 8080
  shutdown: graceful                    # 預設為IMMEDIATE,表示立即關機;GRACEFUL表示優雅關機

management:
  server:
    port: 50000                         # 啟用獨立運維埠
  endpoint:                             # 開啟shutdown和health端點
    shutdown:
      enabled: true
    health:
      probes:
        enabled: true
  endpoints:
    web:
      exposure:
        base-path: /actuator            # 指定上下文路徑,啟用相應端點
        include: health,shutdown

將暴露/actuator/shutdown介面,調用方式如下:

curl -X POST 127.0.0.1:50000/actuator/shutdown
運維層面

確保dockerfile模版集成curl工具,否則無法使用curl命令

FROM openjdk:8-jdk-alpine
#構建參數
ARG JAR_FILE
ARG WORK_PATH="/app"
ARG EXPOSE_PORT=8080

#環境變數
ENV JAVA_OPTS=""\
    JAR_FILE=${JAR_FILE}

#設置時區
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories  \
    && apk add --no-cache curl
#將maven目錄的jar包拷貝到docker中,並命名為for_docker.jar
COPY target/$JAR_FILE $WORK_PATH/


#設置工作目錄
WORKDIR $WORK_PATH


# 指定於外界交互的埠
EXPOSE $EXPOSE_PORT
# 配置容器,使其可執行化
ENTRYPOINT exec java $JAVA_OPTS -jar $JAR_FILE

k8s部署模版deployment.yaml

註:經驗證,java項目可省略結束回調鉤子的配置

此外,若需使用回調鉤子,需保證鏡像中包含curl工具,且需註意應用管理埠(50000)不能暴露到公網

apiVersion: apps/v1
kind: Deployment
spec:
  template:
    spec:
      containers:
      - name: {APP_NAME}
        image: {IMAGE_URL}
        imagePullPolicy: Always
        ports:
        - containerPort: {APP_PORT}
        - containerPort: 50000
        lifecycle:
          preStop:       # 結束回調鉤子
            exec:
              command: ["curl", "-XPOST", "127.0.0.1:50000/actuator/shutdown"]

彈性伸縮

為pod設置資源限制後,創建HPA

apiVersion: apps/v1
kind: Deployment
metadata:
  name: {APP_NAME}
  labels:
    app: {APP_NAME}
spec:
  template:
    spec:
      containers:
      - name: {APP_NAME}
        image: {IMAGE_URL}
        imagePullPolicy: Always
        resources:                     # 容器資源管理
          limits:                      # 資源限制(監控使用情況)
            cpu: 0.5
            memory: 1Gi
          requests:                    # 最小可用資源(靈活調度)
            cpu: 0.15
            memory: 300Mi
---
kind: HorizontalPodAutoscaler            # 彈性伸縮控制器
apiVersion: autoscaling/v2beta2
metadata:
  name: {APP_NAME}
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: {APP_NAME}
  minReplicas: {REPLICAS}                # 縮放範圍
  maxReplicas: 6
  metrics:
    - type: Resource
      resource:
        name: cpu                        # 指定資源指標
        target:
          type: Utilization
          averageUtilization: 50

Prometheus集成

業務層面

項目依賴 pom.xml

<!-- 引入Spring boot的監控機制-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

定義訪問埠、路徑及許可權 application.yaml

management:
  server:
    port: 50000                         # 啟用獨立運維埠
  metrics:
    tags:
      application: ${spring.application.name}
  endpoints:
    web:
      exposure:
        base-path: /actuator            # 指定上下文路徑,啟用相應端點
        include: metrics,prometheus

將暴露/actuator/metric/actuator/prometheus介面,訪問方式如下:

http://127.0.0.1:50000/actuator/metric
http://127.0.0.1:50000/actuator/prometheus
運維層面

deployment.yaml

apiVersion: apps/v1
kind: Deployment
spec:
  template:
    metadata:
      annotations:
        prometheus:io/port: "50000"
        prometheus.io/path: /actuator/prometheus  # 在流水線中賦值
        prometheus.io/scrape: "true"              # 基於pod的服務發現

配置分離

方案:通過configmap掛載外部配置文件,並指定激活環境運行

作用:配置分離,避免敏感信息泄露;鏡像復用,提高交付效率

通過文件生成configmap

# 通過dry-run的方式生成yaml文件
kubectl create cm -n <namespace> <APP_NAME> --from-file=application-test.yaml --dry-run=1 -oyaml > configmap.yaml

# 更新
kubectl apply -f configmap.yaml

掛載configmap並指定激活環境

apiVersion: apps/v1
kind: Deployment
metadata:
  name: {APP_NAME}
  labels:
    app: {APP_NAME}
spec:
  template:
    spec:
      containers:
      - name: {APP_NAME}
        image: {IMAGE_URL}
        imagePullPolicy: Always
        env:
          - name: SPRING_PROFILES_ACTIVE   # 指定激活環境
            value: test
        volumeMounts:                      # 掛載configmap
        - name: conf
          mountPath: "/app/config"         # 與Dockerfile中工作目錄一致
          readOnly: true
      volumes:
      - name: conf
        configMap:
          name: {APP_NAME}

彙總配置

業務層面

項目依賴 pom.xml

<!-- 引入Spring boot的監控機制-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

定義訪問埠、路徑及許可權 application.yaml

spring:
  application:
    name: project-sample
  profiles:
    active: @profileActive@
  lifecycle:
    timeout-per-shutdown-phase: 30s     # 停機過程超時時長設置30s,超過30s,直接停機

server:
  port: 8080
  shutdown: graceful                    # 預設為IMMEDIATE,表示立即關機;GRACEFUL表示優雅關機

management:
  server:
    port: 50000                         # 啟用獨立運維埠
  metrics:
    tags:
      application: ${spring.application.name}
  endpoint:                             # 開啟shutdown和health端點
    shutdown:
      enabled: true
    health:
      probes:
        enabled: true
  endpoints:
    web:
      exposure:
        base-path: /actuator            # 指定上下文路徑,啟用相應端點
        include: health,shutdown,metrics,prometheus

運維層面

確保dockerfile模版集成curl工具,否則無法使用curl命令

FROM openjdk:8-jdk-alpine
#構建參數
ARG JAR_FILE
ARG WORK_PATH="/app"
ARG EXPOSE_PORT=8080

#環境變數
ENV JAVA_OPTS=""\
    JAR_FILE=${JAR_FILE}

#設置時區
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories  \
    && apk add --no-cache curl
#將maven目錄的jar包拷貝到docker中,並命名為for_docker.jar
COPY target/$JAR_FILE $WORK_PATH/


#設置工作目錄
WORKDIR $WORK_PATH


# 指定於外界交互的埠
EXPOSE $EXPOSE_PORT
# 配置容器,使其可執行化
ENTRYPOINT exec java $JAVA_OPTS -jar $JAR_FILE

k8s部署模版deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: {APP_NAME}
  labels:
    app: {APP_NAME}
spec:
  selector:
    matchLabels:
      app: {APP_NAME}
  replicas: {REPLICAS}                            # Pod副本數
  strategy:
    type: RollingUpdate                           # 滾動更新策略
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  template:
    metadata:
      name: {APP_NAME}
      labels:
        app: {APP_NAME}
      annotations:
        timestamp: {TIMESTAMP}
        prometheus.io/port: "50000"               # 不能動態賦值
        prometheus.io/path: /actuator/prometheus
        prometheus.io/scrape: "true"              # 基於pod的服務發現
    spec:
      affinity:                                   # 設置調度策略,採取多主機/多可用區部署
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 100
            podAffinityTerm:
              labelSelector:
                matchExpressions:
                - key: app
                  operator: In
                  values:
                  - {APP_NAME}
              topologyKey: "kubernetes.io/hostname" # 多可用區為"topology.kubernetes.io/zone"
      terminationGracePeriodSeconds: 30             # 優雅終止寬限期
      containers:
      - name: {APP_NAME}
        image: {IMAGE_URL}
        imagePullPolicy: Always
        ports:
        - containerPort: {APP_PORT}
        - name: management-port
          containerPort: 50000         # 應用管理埠
        readinessProbe:                # 就緒探針
          httpGet:
            path: /actuator/health/readiness
            port: management-port
          initialDelaySeconds: 30      # 延遲載入時間
          periodSeconds: 10            # 重試時間間隔
          timeoutSeconds: 1            # 超時時間設置
          successThreshold: 1          # 健康閾值
          failureThreshold: 9          # 不健康閾值
        livenessProbe:                 # 存活探針
          httpGet:
            path: /actuator/health/liveness
            port: management-port
          initialDelaySeconds: 30      # 延遲載入時間
          periodSeconds: 10            # 重試時間間隔
          timeoutSeconds: 1            # 超時時間設置
          successThreshold: 1          # 健康閾值
          failureThreshold: 6          # 不健康閾值
        resources:                     # 容器資源管理
          limits:                      # 資源限制(監控使用情況)
            cpu: 0.5
            memory: 1Gi
          requests:                    # 最小可用資源(靈活調度)
            cpu: 0.1
            memory: 200Mi
        env:
          - name: TZ
            value: Asia/Shanghai
---
kind: HorizontalPodAutoscaler            # 彈性伸縮控制器
apiVersion: autoscaling/v2beta2
metadata:
  name: {APP_NAME}
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: {APP_NAME}
  minReplicas: {REPLICAS}                # 縮放範圍
  maxReplicas: 6
  metrics:
    - type: Resource
      resource:
        name: cpu                        # 指定資源指標
        target:
          type: Utilization
          averageUtilization: 50

近期熱文推薦:

1.1,000+ 道 Java面試題及答案整理(2022最新版)

2.勁爆!Java 協程要來了。。。

3.Spring Boot 2.x 教程,太全了!

4.別再寫滿屏的爆爆爆炸類了,試試裝飾器模式,這才是優雅的方式!!

5.《Java開發手冊(嵩山版)》最新發佈,速速下載!

覺得不錯,別忘了隨手點贊+轉發哦!


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • ## Mybatis ### 舉個小慄子 mybatis配置文件(XML配置文件) ```java ``` user.xml(實現增刪改查的sql語句) ```xml insert into user values (#{userId},#{username},#{password}) delete ...
  • [toc] > 技術和工具「!喜新厭舊」 # 一、背景 最近在一個輕量級的服務中,嘗試了最新的技術和工具選型; 即`SpringBoot3`,`JDK17`,`IDEA2023`,`Navicat16`,雖然新的技術和工具都更加強大和高效,但是適應採坑的過程總是枯燥的; 【環境一覽】 ![](htt ...
  • 多態是Java語言極為重要的一個特性,可以說是Java語言動態性的根本,那麼線程執行一個方法時到底在記憶體中經歷了什麼,JVM又是如何確定方法執行版本的呢? ...
  • ## 教程簡介 Ext JS是一個流行的JavaScript框架,它為使用跨瀏覽器功能構建Web應用程式提供了豐富的UI。 Ext JS基本上用於創建桌面應用程式它支持所有現代瀏覽器,如IE6 +,FF,Chrome,safari 6+ 等。Ext JS基於MVC / MVVM架構。 最新版本的Ex ...
  • 本文翻譯自國外論壇 medium,原文地址:https://medium.com/@raviyasas/spring-boot-best-practices-for-developers-3f3bdffa0090 Spring Boot 是一種廣泛使用且非常流行的企業級高性能框架。以下是一些最佳實踐 ...
  • 對於個人建站來說,WordPress相信很多讀者都知道了。但WordPress很多時候我們還是用來建立自主發佈內容的站點為主,適用於個人博客、企業主站等。雖然有的主題可以把WordPress變為論壇,但效果並不是很好。 所以,今天給大家推薦一個開源的論壇項目: [**vanilla**](https ...
  • 在開始主題前,先看一個 C++ 例子: #include <iostream> struct Data { int a; int b; }; // 註意這裡 struct Data *s; void doSome() { Data k; k.a = 100; k.b = 300; // 註意這裡,會 ...
  • # 整體架構 ![](https://img2023.cnblogs.com/blog/1258602/202308/1258602-20230807095950782-1096148976.jpg) ![](https://img2023.cnblogs.com/blog/1258602/2023 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...