PropertySource 過載

此功能在 2020.0 版本中已被棄用。請參閱 Spring Cloud Kubernetes Configuration Watcher 控制器,以獲取實現相同功能的替代方法。

一些應用程式可能需要檢測外部屬性源的變化,並更新其內部狀態以反映新的配置。Spring Cloud Kubernetes 的過載功能能夠在相關的 ConfigMapSecret 更改時觸發應用程式過載。

預設情況下,此功能是停用的。您可以透過使用 spring.cloud.kubernetes.reload.enabled=true 配置屬性(例如,在 application.properties 檔案中)啟用它。請注意,這將只啟用對配置對映的監控(即:spring.cloud.kubernetes.reload.monitoring-config-maps 將設定為 true)。如果您想啟用對 Secrets 的監控,必須透過 spring.cloud.kubernetes.reload.monitoring-secrets=true 明確進行設定。

支援以下級別的過載(透過設定 spring.cloud.kubernetes.reload.strategy 屬性)

  • refresh(預設):只重新載入使用 @ConfigurationProperties@RefreshScope 註解的配置 bean。此過載級別利用了 Spring Cloud Context 的重新整理功能。

  • restart_context:整個 Spring ApplicationContext 將優雅地重啟。Bean 將使用新配置重新建立。為了使重啟上下文功能正常工作,您必須啟用並暴露重啟執行器端點。

management:
  endpoint:
    restart:
      enabled: true
  endpoints:
    web:
      exposure:
        include: restart
  • shutdown:Spring ApplicationContext 將被關閉以啟用容器的重啟。當您使用此級別時,請確保所有非守護執行緒的生命週期都繫結到 ApplicationContext,並且配置了複製控制器或副本集以重啟 Pod。

假設過載功能以預設設定(refresh 模式)啟用,當配置對映更改時,以下 bean 將被重新整理。

@Configuration
@ConfigurationProperties(prefix = "bean")
public class MyConfig {

    private String message = "a message that can be changed live";

    // getter and setters

}

為了看到更改確實發生,您可以建立另一個 bean,它會定期列印訊息,如下所示

@Component
public class MyBean {

    @Autowired
    private MyConfig config;

    @Scheduled(fixedDelay = 5000)
    public void hello() {
        System.out.println("The message is: " + config.getMessage());
    }
}

您可以使用 ConfigMap 更改應用程式列印的訊息,如下所示

apiVersion: v1
kind: ConfigMap
metadata:
  name: reload-example
data:
  application.properties: |-
    bean.message=Hello World!

與 Pod 關聯的 ConfigMap 中名為 bean.message 的屬性的任何更改都會反映在輸出中。更一般地說,與 @ConfigurationProperties 註解的 prefix 欄位定義的值字首相關的屬性更改將被檢測並反映在應用程式中。ConfigMap 與 Pod 關聯 在本章前面已解釋。

過載功能支援兩種操作模式

  • 事件(預設):使用 Kubernetes API(WebSocket)監視 ConfigMap 或 Secret 中的更改。任何事件都會觸發配置的重新檢查,如果發生更改,則會觸發過載。需要服務賬戶具有 view 角色才能監聽 ConfigMap 更改。對於 Secret,需要更高級別的角色(例如 edit)(預設情況下,Secret 不受監控)。

  • 輪詢:定期從 ConfigMap 和 Secret 重新建立配置,以檢視其是否已更改。您可以使用 spring.cloud.kubernetes.reload.period 屬性配置輪詢週期,預設為 15 秒。它需要與受監控屬性源相同的角色。這意味著,例如,對檔案掛載的 Secret 源使用輪詢不需要特殊的許可權。

© . This site is unofficial and not affiliated with VMware.