Spring配置服务器在运行时添加属性

4
我希望在运行时在Spring配置服务器中添加一些属性,并且这些属性应该通过@Value注释对所有客户端应用程序可用。
我不会预定义此属性,因为我将在Spring配置服务器中计算该值并添加到环境变量中。
您能否帮助我了解最佳实现方法?

请查看此答案:https://dev59.com/aZjga4cB1Zd3GeqPFRvT#37873783 - Pär Nilsson
可能是Spring Cloud Config Server + RabbitMQ的重复问题。 - Raz0rwire
1
不好意思,这是一个不同的问题。 - Manoj Dubey
1个回答

3

Spring Cloud Configuration有一个名为'RefreshScope'的特性,可以刷新正在运行的应用程序的属性和bean。

如果您了解Spring Cloud Config,它似乎只能从git存储库加载属性,但这并不是真的。

您可以使用RefreshScope从本地文件重新加载属性,而无需连接到外部git存储库或进行HTTP请求。

创建一个名为bootstrap.properties的文件,并写入以下内容:

# false: spring cloud config will not try to connect to a git repository
spring.cloud.config.enabled=false
# let the location point to the file with the reloadable properties
reloadable-properties.location=file:/config/defaults/reloadable.properties

在您定义的位置创建一个名为reloadable.properties的文件。您可以将其留空或添加一些属性。在此文件中,稍后可以在运行时更改或添加属性。
添加依赖项:
 <dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-config</artifactId>
 </dependency>

所有使用可能在运行时更改的属性的bean都应该像这样用 @RefreshScope 进行注释:

@Bean
@RefreshScope
Controller controller() {
    return new Controller();
}

创建一个类
public class ReloadablePropertySourceLocator implements PropertySourceLocator
{
       private final String location;

       public ReloadablePropertySourceLocator(
           @Value("${reloadable-properties.location}") String location) {
           this.location = location;
        }

    /**
     * must create a new instance of the property source on every call
     */
    @Override
    public PropertySource<?> locate(Environment environment) {
        try {
            return new ResourcePropertySource(location);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

将 Spring 配置成使用该类引导配置

在您的资源文件夹中创建(或扩展)META-INF/spring.factories 文件:

org.springframework.cloud.bootstrap.BootstrapConfiguration=your.package.ReloadablePropertySourceLocator

这个bean将从reloadable.properties中读取属性。当刷新应用程序时,Spring Cloud Config将从磁盘重新加载它。
添加运行时,根据需要编辑reloadable.properties,然后刷新spring上下文。您可以通过向/refresh端点发送POST请求或使用ContextRefresher在Java中刷新。
@Autowired
ContextRefresher contextRefresher;
...
contextRefresher.refresh();

如果您选择与来自远程git仓库的属性并行使用,这也应该可以工作。


1
感谢Stefan的回复。我理解你建议我们可以将运行时属性添加到外部文件中,Spring配置服务器将自动加载它。但是,是否有可能在不写入文件的情况下实现这一点呢? 我们是否可以通过environment.addPorperty(key, Value)这样的方式来做到,以便所有配置客户端都可以使用它? - Manoj Dubey
可以在项目全局范围内完成,而不是使用@RefreshScope定义bean吗? - Ankit Bansal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接