【问题标题】:Spring Cloud Configuration Client not refreshing propertiesSpring Cloud Configuration Client 不刷新属性
【发布时间】:2021-01-30 18:58:55
【问题描述】:

我有一个配置服务器和一个 Spring Boot 2.3.1 应用程序连接到服务器以加载正确配置文件的配置属性。

配置服务器使用 git 获取每个应用程序和配置文件的配置文件。

这没问题,当 Spring Boot 应用程序启动时,它会从配置服务器加载正确的属性值。

当我更新配置文件中的值并将其推送到 git,然后执行 Spring Boot 应用程序的 Post/actuator/refresh 端点时,我看到返回的 json 带有我更新的属性的名称,即我所期望的。

问题是属性实际上并没有在那之后更新。它们保持旧值。

例如:

@Service
//@RefreshScope
public class WhitelistService {
  private static final Logger log = LoggerFactory.getLogger(WhitelistService.class);

  private final WhitelistRepository whitelistRepository;
  private final Boolean isWhitelistEnabled;
  private final Integer identifier;

  @Autowired
  public WhitelistService(WhitelistRepository whitelistRepository,
        @Value("${app.whitelist.isEnabled:true}") Boolean isWhitelistEnabled,
        @Value("${app.whitelist.identifier:-1}") Integer identifier) {
    super();
    this.whitelistRepository = whitelistRepository;
    this.isWhitelistEnabled = isWhitelistEnabled;
    this.identifier = identifier;
  }

  public boolean processBasedOnWhitelist(Long id) {
    if (!isWhitelistEnabled)
        return true;
    else if (identifier <= -1)
        return isInWhitelist(id);
    else
        return isInWhitelistWithIdentifier(id, identifier);
  }

 }

如果@RefreshScope 如上所述被注释掉,我在适当的属性文件中更新app.whitelist.isEnabled 并将其推送到配置文件并执行actuator/refresh 然后app.whitelist.isEnabled 保留旧值。

即使我在值字段中使用setter 或只是在声明期间使用@Value 注释字段本身也是如此。

如果我启用@RefreshScope,值会按预期更新。

但是,上次我使用 Configuration Server 和 Spring Boot 作为客户端时,在另一个项目中,情况并非如此(除非在 Spring Boot 2.3.1 中发生了变化)。以前不需要@RefreshScope,就可以立即更新。

我错过了什么吗?我想避免向我有属性值引用的每个 Bean 添加另一个注释。这没什么大不了的,但似乎没有必要且容易出错。

【问题讨论】:

    标签: spring spring-boot spring-cloud spring-cloud-config


    【解决方案1】:

    在 Spring Cloud Bus 文档中:https://cloud.spring.io/spring-cloud-static/spring-cloud-bus/2.1.0.RELEASE/single/spring-cloud-bus.html#_bus_refresh_endpoint

    /actuator/bus-refresh 端点清除 RefreshScope 缓存并重新绑定 @ConfigurationProperties。有关详细信息,请参阅刷新范围文档。

    所以要么你的 bean 使用 @RefreshScope 注释,要么它具有 @ConfigurationProperties 注释。由于您的 bean 没有使用 @ConfigurationProperties 注释,因此它必须使用 @RefreshScope 注释才能刷新它。

    很可能,在您的其他项目中,您的 bean 将使用 @ConfigurationProperties 进行注释

    【讨论】:

    • 这与 Spring Boot 1.x 有什么不同吗?因为在另一个项目中,除了@Component@Service 在我的课程中,我肯定没有任何注释
    • 乔迪是正确的。您要么需要@RefreshScope,要么使用@ConfigurationProperties
    猜你喜欢
    • 2015-01-23
    • 2012-05-19
    • 2016-02-07
    • 2014-12-30
    • 2019-01-24
    • 2021-04-13
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    相关资源
    最近更新 更多