java – 用dropwizard覆盖具有env变量的服务器连接器配置

前端之家收集整理的这篇文章主要介绍了java – 用dropwizard覆盖具有env变量的服务器连接器配置前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经在dw邮件列表中发布了这个问题,但没有得到答案.

我可以假定下面的YML格式不再适用于DW 0.7.0了吗? (使用@ char插入env var)

server:
  applicationConnectors:
    - type: http
      bindHost: @OPENSHIFT_DIY_IP@
      port: @OPENSHIFT_DIY_PORT@

错误

Malformed YAML at line: 28,column: 17; while scanning for the next token; found character @ ‘@’ that cannot start any token. (Do not use @ for indentation); in ‘reader’,line 28,column 17:
bindHost: @OPENSHIFT_DIY_IP@

所以我决定使用这种格式:

server:
  type: simple
  applicationContextPath: /
  adminContextPath: /admin
  connector:
      type: http
      bindHost: localhost
      port: 8080

并试图通过jvm选项覆盖它:

java -Ddw.server.connector.bindHost=$OPENSHIFT_DIY_IP -Ddw.server.connector.port=$OPENSHIFT_DIY_PORT -jar target/myapp.jar server myapp.yml

我的本地env变量:

OPENSHIFT_DIY_IP=localhost
OPENSHIFT_DIY_PORT=8080

我从这个设置得到的错误

Exception in thread “main” java.lang.RuntimeException: java.net.SocketException: Unresolved address
at org.eclipse.jetty.setuid.SetUIDListener.lifeCycleStarting(SetUIDListener.java:213)

Caused by: java.net.SocketException: Unresolved address
at sun.nio.ch.Net.translateToSocketException(Net.java:157)

WARN [2014-05-03 20:11:19,412] org.eclipse.jetty.util.component.AbstractLifeCycle: Failed org.eclipse.jetty.server.Server@91b85: java.lang.RuntimeException: java.net.SocketException: Unresolved address

我究竟做错了什么?

解决方法

从Dropwizard版本0.8.0开始,您可以从配置yml文件访问环境变量.它还支持设置默认值,以防环境变量不可用.
See the docs here.

// put environment variable inside ${}
// use :- operator to provide default value

dbHost: ${DB_HOST}
dbPort: ${DB_PORT:-1234}
// dbPort = 1234,if DB_PORT environment variable has no value

重要注意事项:为了使其工作,您需要使用EnvironmentVariableSubstitutor设置一个SubstituingSourceProvider.

// Enable variable substitution with environment variables
bootstrap.setConfigurationSourceProvider(
    new SubstitutingSourceProvider(
        bootstrap.getConfigurationSourceProvider(),new EnvironmentVariableSubstitutor())
);

猜你在找的Java相关文章