【问题标题】:Microprofile Config using dynamic config-keys使用动态配置键的 Microprofile 配置
【发布时间】:2019-02-12 17:07:48
【问题描述】:

我目前正在寻找一种动态组装配置键(回退处理)的方法,然后在我们的 microprofile-config.properties 文件中查找它们。这样的文件可能如下所示:

# customer fallbacks

my.config=1234                            # use this fallback when there is no customer
customer2.my.config=12345                 # use this fallback when there is no subcustomer
customer2.subCustomer1.my.config=123456   # first level

所以当有一个客户和一个子客户时,就用on

我遇到这个问题的原因是我想使用@ConfigProperty 注释,所以没有 ConfigProvider.getConfig()。这意味着我必须在我的自定义 ConfigSource 中组装我的动态配置密钥。

我知道 ConfigSources 是通过 ServiceLoader 在服务器启动时加载的。所以我尝试删除现有的配置并将其替换为我的自定义配置:

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;

import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;

@Startup
@Singleton
public class StartupConfigurationRegistrar{

@PostConstruct
private void registerConfig() {
        final Config customConfig = ConfigProviderResolver.instance().getBuilder().withSources(new FallbackHandlingConfiguration(myReqiredVariables)).addDefaultSources().build();
        ConfigProviderResolver.instance().releaseConfig(ConfigProviderResolver.instance().getConfig());
        ConfigProviderResolver.instance().registerConfig(customConfig, Thread.currentThread().getContextClassLoader());
    }
}

我的 ConfigSource 已正确添加。但后来当尝试访问不同类中的配置时,我的自定义 ConfigSource 消失了,只剩下三个默认的 ConfigSource。我认为这可能是 ClassLoader 的问题。

知道如何在ConfigSource 中获取动态值吗?

【问题讨论】:

    标签: jakarta-ee config microprofile


    【解决方案1】:

    您对ConfigBuilder 有一点误解。如果您使用它来创建Config,那么您必须手动传递它。

    但大多数时候您通常使用我们的“自动发现”模式。这适用于标准的java.util.ServiceLoader 机制。它在规范 PDF 和 JavaDocs 中有描述:https://github.com/eclipse/microprofile-config/blob/master/api/src/main/java/org/eclipse/microprofile/config/spi/ConfigSource.java#L64

    但我宁愿没有动态值的 ConfigSource,因为这可能会在高并发负载下造成麻烦。 您可能更愿意看一下我们为 ConfigJSR 提出的 addLookupSuffix 机制,现在正在移植回 mp-config: https://github.com/eclipse/ConfigJSR/blob/master/api/src/main/java/javax/config/ConfigAccessor.java#L191

    这与您最初的想法相似,但 .customer2 将是 config 键的后缀。 hth。

    【讨论】:

      猜你喜欢
      • 2019-12-08
      • 2021-06-10
      • 1970-01-01
      • 2017-05-03
      • 1970-01-01
      • 2022-08-11
      • 2016-07-21
      • 2020-09-28
      • 2021-09-02
      相关资源
      最近更新 更多