我可以在DropWizard中拥有多个配置文件吗?

Vic*_*nin 14 java dropwizard

我想为DropWizard提供几个yaml文件.其中一个包含敏感信息,一个包含非敏感信息.

你能指点我的任何文档或例子如何在DropWizard中有多个配置吗?

Nat*_*tan 8

ConfigurationSourceProvider 是你的答案.

bootstrap.setConfigurationSourceProvider(new MyMultipleConfigurationSourceProvider());
Run Code Online (Sandbox Code Playgroud)

以下是dropwizard默认情况下的工作方式.您可以根据自己的喜好轻松更改它.

public class FileConfigurationSourceProvider implements ConfigurationSourceProvider {
    @Override
    public InputStream open(String path) throws IOException {
        final File file = new File(path);
        if (!file.exists()) {
            throw new FileNotFoundException("File " + file + " not found");
        }

        return new FileInputStream(file);
    }
}
Run Code Online (Sandbox Code Playgroud)


ko2*_*2ic 5

首先,您将在a中编写另一个yml文件路径.yml.

sample.yml

configPath: /another.yml
Run Code Online (Sandbox Code Playgroud)

another.yml

greet: Hello!
Run Code Online (Sandbox Code Playgroud)

只需使用SnakeYaml即可解决问题.

public void run(SampleConfiguration configuration, Environment environment) {
    Yaml yaml = new Yaml();
    InputStream in = getClass().getResourceAsStream(configuration.getConfigPath());
    AnotherConfig anotherConfig = yaml.loadAs(in, AnotherConfig.class);
    String str = anotherConfig.getGreet(); // Hello!
...
}
Run Code Online (Sandbox Code Playgroud)

对于敏感信息,我认为使用环境变量是好的.

例如,使用dropwizard-environment-config
https://github.com/tkrille/dropwizard-environment-config


yun*_*ace 5

理想情况下,您应该通过将敏感信息或可配置数据放在环境变量中来配置应用程序,而不是管理多个文件.请参阅配置中的十二个因子规则:http://12factor.net/config

要在Dropwizard中启用此方法,您可以使用-Ddw标志在运行时使用环境变量覆盖您的配置:

java -Ddw.http.port=$PORT -jar yourapp.jar server yourconfig.yml
Run Code Online (Sandbox Code Playgroud)

或者您可以使用这个方便的添加:https://github.com/tkrille/dropwizard-template-config将环境变量占位符放在您的配置中:

server:
  type: simple
  connector:
    type: http
    # replacing environment variables
    port: ${env.PORT}
Run Code Online (Sandbox Code Playgroud)

上述两种解决方案都与Heroku和Docker容器兼容,其中环境变量仅在您运行应用程序时可用.

  • ...例如Pupplet,Chef,Ansible等.最终的想法是将您的开发人员问题与Ops分开,以便不将凭证检入源代码,可以独立审计安全性,并且可以在基础架构级别完成环境更改而不是挖掘每个源代码配置文件.共享变量文件也可以工作,但是如何更好?这意味着您的配置需要代码来读取每个服务中的变量,其中DW配置支持Env Var开箱即用.此外,Env Vars还可以使用Docker/Heroku等不可变容器的Continuous Delivery (2认同)
  • 对于具有每个环境更改的大量配置的应用程序,系统变量将是一场噩梦. (2认同)