PropertySource
過載
此功能在 2020.0 版本中已棄用。請參閱 Spring Cloud Kubernetes Configuration Watcher 控制器,以瞭解實現相同功能的替代方法。 |
某些應用程式可能需要檢測外部屬性源的更改並更新其內部狀態以反映新配置。Spring Cloud Kubernetes 的過載功能能夠在相關的 ConfigMap
或 Secret
發生更改時觸發應用程式過載。
預設情況下,此功能是停用的。您可以使用配置屬性 spring.cloud.kubernetes.reload.enabled=true
來啟用它(例如,在 application.properties
檔案中)。請注意,這將僅啟用對 configmaps 的監控(即: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
: 整個 SpringApplicationContext
會被優雅地重啟。Bean 將使用新配置重新建立。為了使重啟上下文功能正常工作,您必須啟用並暴露 restart actuator endpoint。
management: endpoint: restart: enabled: true endpoints: web: exposure: include: restart
-
shutdown
: SpringApplicationContext
會被關閉以啟用容器的重啟。當您使用此級別時,請確保所有非守護執行緒的生命週期都繫結到ApplicationContext
,並且配置了 replication controller 或 replica set 來重啟 pod。
假設過載功能已啟用預設設定(refresh
模式),當 config map 更改時,以下 Bean 將被重新整理:
@Configuration @ConfigurationProperties(prefix = "bean") public class MyConfig { private String message = "a message that can be changed live"; // getter and setters }
為了看到更改實際發生,您可以建立另一個 Bean,該 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 (web socket) 監視 config maps 或 secrets 的變化。任何事件都會觸發對配置的重新檢查,如果發生變化,則觸發過載。需要 service account 具有
view
角色才能監聽 config map 的變化。對於 secrets,需要更高級別的角色(例如edit
)(預設情況下不監控 secrets)。 -
輪詢模式: 定期從 config maps 和 secrets 中重新建立配置,以檢視是否發生變化。您可以使用屬性
spring.cloud.kubernetes.reload.period
配置輪詢週期,預設值為 15 秒。它需要與被監控的屬性源相同的角色。這意味著,例如,對檔案掛載的 secret 源使用輪詢不需要特殊許可權。