PropertySource重新加载

此功能在 2020.0 版本中已弃用。请参阅 Spring Cloud Kubernetes Configuration Watcher 控制器,以实现相同功能的另一种方法。

某些应用程序可能需要检测外部属性源上的更改并更新其内部状态以反映新配置。 Spring Cloud Kubernetes 的 reload 功能能够在相关的ConfigMapSecret变化。spring-doc.cadn.net.cn

默认情况下,此功能处于禁用状态。您可以使用spring.cloud.kubernetes.reload.enabled=trueconfiguration 属性(例如,在application.properties文件)。 请注意,这将仅启用对 configmap 的监控(即:spring.cloud.kubernetes.reload.monitoring-config-maps将设置为true). 如果要启用密钥监控,则必须通过以下方式显式完成:spring.cloud.kubernetes.reload.monitoring-secrets=true.spring-doc.cadn.net.cn

支持以下级别的重新加载(通过将spring.cloud.kubernetes.reload.strategyproperty) 的spring-doc.cadn.net.cn

  • refresh(默认):仅带有@ConfigurationProperties@RefreshScope重新加载。 此重新加载级别利用 Spring Cloud Context 的刷新功能。spring-doc.cadn.net.cn

  • restart_context:整个SpringApplicationContext将正常重新启动。使用新配置重新创建 Bean。 为了使 restart context 功能正常工作,您必须启用并公开 restart actuator 端点spring-doc.cadn.net.cn

management:
  endpoint:
    restart:
      enabled: true
  endpoints:
    web:
      exposure:
        include: restart
  • shutdown: 弹簧ApplicationContext已关闭以激活容器的重新启动。 使用此级别时,请确保所有非守护进程线程的生命周期都绑定到ApplicationContext以及将复制控制器或副本集配置为重新启动 Pod。spring-doc.cadn.net.cn

假设使用默认设置 (refresh模式),当 config map 更改时,将刷新以下 Bean:spring-doc.cadn.net.cn

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

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

    // getter and setters

}

要查看更改有效地发生,您可以创建另一个定期打印消息的 bean,如下所示spring-doc.cadn.net.cn

@Component
public class MyBean {

    @Autowired
    private MyConfig config;

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

您可以使用ConfigMap如下:spring-doc.cadn.net.cn

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

对名为bean.messageConfigMap与 Pod 关联的 Pod 反映在 输出。更一般地说,与以prefix字段的@ConfigurationProperties注释被检测并反映在应用程序中。ConfigMap带 Pod在本章前面进行了解释。spring-doc.cadn.net.cn

重新加载功能支持两种作模式:spring-doc.cadn.net.cn

  • 事件 (默认):使用 Kubernetes API (Web 套接字) 监视配置映射或 secret 中的更改。 任何事件都会对配置产生重新检查,如果发生更改,则会重新加载。 这viewrole,才能侦听 Config Map 更改。更高级别的角色(例如edit) 是密钥所必需的 (默认情况下,不监控密钥)。spring-doc.cadn.net.cn

  • 轮询:定期从配置映射和密钥重新创建配置,以查看其是否已更改。 您可以使用spring.cloud.kubernetes.reload.period属性,默认为 15 秒。 它需要与受监控属性源相同的角色。 这意味着,例如,对文件挂载的密钥源使用轮询不需要特定权限。spring-doc.cadn.net.cn