我想为DropWizard提供几个yaml文件。其中一个包含敏感信息,一个包含非敏感信息。
你能指点我的任何文档或示例如何在DropWizard中有多个配置吗?
我想为DropWizard提供几个yaml文件。其中一个包含敏感信息,一个包含非敏感信息。
你能指点我的任何文档或示例如何在DropWizard中有多个配置吗?
ConfigurationSourceProvider
是你的答案。
bootstrap.setConfigurationSourceProvider(new MyMultipleConfigurationSourceProvider());
以下是如何做到的 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);
}
}
ConfigurationSourceProvider
是你的答案。
bootstrap.setConfigurationSourceProvider(new MyMultipleConfigurationSourceProvider());
以下是如何做到的 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);
}
}
首先,您将在a中编写另一个yml文件路径 .yml
。
sample.yml
configPath: /another.yml
another.yml
greet: Hello!
只需使用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!
...
}
对于敏感信息,我认为使用环境变量是好的。
例如,使用dropwizard-environment-config
https://github.com/tkrille/dropwizard-environment-config
理想情况下,您应该通过将敏感信息或可配置数据放入其中来配置应用程序 环境变量而不是管理多个文件。请参阅配置中的十二个因子规则 http://12factor.net/config
要在Dropwizard中启用此方法,您可以使用在运行时使用环境变量覆盖您的配置 -Ddw
旗:
java -Ddw.http.port=$PORT -jar yourapp.jar server yourconfig.yml
或者您可以使用这个方便的添加: https://github.com/tkrille/dropwizard-template-config 将环境变量占位符放在配置中:
server:
type: simple
connector:
type: http
# replacing environment variables
port: ${env.PORT}
上述两种解决方案都与Heroku和Docker容器兼容,其中环境变量仅在您运行应用程序时可用。