首页 > 解决方案 > Spring Cloud Configuration Client 不刷新属性

问题描述

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

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

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

当我更新配置文件中的值并将其推送到 git 然后执行Post/actuator/refreshSpring Boot 应用程序的端点时,我看到返回的 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在适当的属性文件中更新并将其推送到配置文件并执行 aactuator/refresh然后app.whitelist.isEnabled保留旧值。

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

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

但是,上次我使用配置服务器和 Spring Boot 作为客户端时,在另一个项目中,情况并非如此(除非在 Spring Boot 2.3.1 中发生了变化)。它过去可以立即更新而无需@RefreshScope.

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

标签: springspring-bootspring-cloudspring-cloud-config

解决方案


在 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 进行注释


推荐阅读