此版本仍在开发中,尚未被视为稳定版本。如需最新的稳定版本,请使用 Spring Cloud Kubernetes 3.1.4! |
PropertySource
重新加载
此功能在 2020.0 版本中已弃用。请参阅 Spring Cloud Kubernetes Configuration Watcher 控制器,以实现相同功能的另一种方法。 |
某些应用程序可能需要检测外部属性源上的更改并更新其内部状态以反映新配置。
Spring Cloud Kubernetes 的 reload 功能能够在相关的ConfigMap
或Secret
变化。
默认情况下,此功能处于禁用状态。您可以使用spring.cloud.kubernetes.reload.enabled=true
configuration 属性(例如,在application.properties
文件)。
请注意,这将仅启用对 configmap 的监控(即:spring.cloud.kubernetes.reload.monitoring-config-maps
将设置为true
).
如果要启用密钥监控,则必须通过以下方式显式完成:spring.cloud.kubernetes.reload.monitoring-secrets=true
.
支持以下级别的重新加载(通过将spring.cloud.kubernetes.reload.strategy
property) 的
-
refresh
(默认):仅带有@ConfigurationProperties
或@RefreshScope
重新加载。 此重新加载级别利用 Spring Cloud Context 的刷新功能。 -
restart_context
:整个SpringApplicationContext
将正常重新启动。使用新配置重新创建 Bean。 为了使 restart context 功能正常工作,您必须启用并公开 restart actuator 端点
management: endpoint: restart: enabled: true endpoints: web: exposure: include: restart
-
shutdown
: 弹簧ApplicationContext
已关闭以激活容器的重新启动。 使用此级别时,请确保所有非守护进程线程的生命周期都绑定到ApplicationContext
以及将复制控制器或副本集配置为重新启动 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,如下所示
@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!
对名为bean.message
在ConfigMap
与 Pod 关联的 Pod 反映在
输出。更一般地说,与以prefix
字段的@ConfigurationProperties
注释被检测并反映在应用程序中。将ConfigMap
带 Pod在本章前面进行了解释。
重新加载功能支持两种作模式:
-
事件 (默认):使用 Kubernetes API (Web 套接字) 监视配置映射或 secret 中的更改。 任何事件都会对配置产生重新检查,如果发生更改,则会重新加载。 这
view
role,才能侦听 Config Map 更改。更高级别的角色(例如edit
) 是密钥所必需的 (默认情况下,不监控密钥)。 -
轮询:定期从配置映射和密钥重新创建配置,以查看其是否已更改。 您可以使用
spring.cloud.kubernetes.reload.period
属性,默认为 15 秒。 它需要与受监控属性源相同的角色。 这意味着,例如,对文件挂载的密钥源使用轮询不需要特定权限。