天天看點

如何讓Spring Boot提供K8s的就緒狀态探測和活動狀态探測

作者:SpringBoot汪雲飛

使用Kubernetes的主要好處之一是它能夠管理和維護在叢集中運作的容器,且能保證幾乎沒有停機時間。

而這個功能主要是k8s通過探測程式的就緒狀态(readiness)和活動狀态(liveness)來實作對程式的健康進行管理的。

在本文中,我們将使用Spring Boot Actuator為我們提供的端點來為K8s提供活動狀态(liveness)和就緒狀态(readiness)的探測,我們将探讨如何使用k8s内置的活動狀态和就緒狀态探測來管理和控制應用程式的運作狀況。Spring Boot自2.3版本開始提供了此功能。

什麼是就緒狀态探測(Readiness Probe)

在 Kubernetes 中,“就緒狀态”探測是一種機制,用于确定容器是否準備好接受流量并處理請求。 “就緒狀态”探測用于確定一個容器已經準備好可以開始接收請求,通常用于在容器啟動後執行一些額外的操作(例如預熱緩存、加載配置檔案等)。

在 Kubernetes 中,如果所有容器都在正常運作并通過了其各自的“就緒狀态”探測,Pod 會被标記為“就緒”。如果一個容器的就緒狀态探測失敗,它将被标記為“未就緒”,并且 Kubernetes将不會将流量路由到該容器。這可以確定Pod隻有在所有容器都準備好處理流量時才能被視為“就緒”,進而提高應用程式的可用性和穩定性。

什麼是活動狀态探測(Liveness Probe)

在 Kubernetes 中,“活動狀态”探測是一種用于檢測應用程式是否正在運作的機制。它通過定時向容器發送HTTP請求或執行指令來檢查容器内的應用程式是否仍然處于運作狀态。如果應用程式沒有響應或者傳回了錯誤的響應,那麼Kubernetes将視為該容器已經死亡,并且将自動重新開機容器,以確定應用程式始終處于運作狀态。

如何讓Spring Boot提供就緒狀态和活動狀态

Spring Boot Actuator為我們提供的端點來為K8s提供活動狀态(liveness)和就緒狀态(readiness)的探測。

如何讓Spring Boot提供K8s的就緒狀态探測和活動狀态探測

Spring Boot和K8s

我們隻需要在我們的程式裡添加依賴:

Gradle:

implementation 'org.springframework.boot:spring-boot-starter-actuator'           

Maven:

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

在application.properties 裡開啟兩個狀态:

management.endpoint.health.probes.enabled=true           

當使用這個配置後,Spring Boot将會暴露“就緒狀态”和“使用狀态”兩個端點:

/actuator/health/liveness
/actuator/health/readiness           

本地啟動可以通路:

http://ip:port/actuator/health/liveness
http://ip:port/actuator/health/readiness           
如何讓Spring Boot提供K8s的就緒狀态探測和活動狀态探測

liveness

如何讓Spring Boot提供K8s的就緒狀态探測和活動狀态探測

readiness

修改k8s的deployment.yml :

apiVersion: apps/v1
kind: Deployment
metadata:
  name: spring-boot-actuator-endpoint
spec:
  selector:
    matchLabels:
      app: spring-boot-actuator-endpoint
  replicas: 1
  template:
    metadata:
      labels:
        app: spring-boot-actuator-endpoint
    spec:
      containers:
        - name: spring-boot-actuator-endpoint
          image: spring-boot-actuator-endpoint:0.0.2
          imagePullPolicy: IfNotPresent
          ports:
            - containerPort: 8080
          livenessProbe:
            httpGet:
              path: /actuator/health/liveness # 1
              port: 8080
            initialDelaySeconds: 20
            periodSeconds: 3
          readinessProbe:
            httpGet:
              path: /actuator/health/readiness # 2
              port: 8080
            initialDelaySeconds: 20 # 3
            periodSeconds: 3 # 4           
  1. 将Spring Boot Actuator的liveness端口填寫在此處。
  2. 将Spring Boot Actuator的readiness端口填寫在此處。
  3. initialDelaySeconds 在執行第一次探測前應該等待 20秒。
  4. periodSeconds 每隔3秒執行一次探測。

當使用新的deployment.yml部署或者更新項目時,k8s就會使用這兩個端點對程式的就緒狀态和活動狀态進行檢測。

繼續閱讀