java—从命令行启动jar时从命令行获取配置属性

cwdobuhd  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(580)

我尝试在本地和heroku上启动vert.x示例(使用procfile): java -Dhttp.port=$PORT -jar myapp.jar 我的经验是,属性(http.port)没有设置,因此无法访问我的程序。
使用system.getenv()读取端口环境变量是可行的,但不是“最佳实践”。
为什么?我能做什么?爱

vsaztqbk

vsaztqbk1#

最好的方法是定义一个json文件并在其中添加所有与配置相关的vertx。
启动应用程序时将config.json作为参数传递。
以下是示例:
config.json文件

{
  "port": 8090
  // you can add other stuff over here
}

运行应用程序时将config.json作为参数传递
java-jar myapp.jar--conf=/path到config.json
所以你可以在你的主页上阅读这个json文件

public class MainVerticle extends AbstractVerticle {

 @Override
  public void start(Future<Void> startFuture) throws Exception {

   JsonObject data = this.config(); 

  // read port and other configuration related stuff from JsonObject 
 }
}

我希望这能帮助你:)

jmp7cifd

jmp7cifd2#

正如@dpr所指出的,configretriever是一条出路。
以下是我最后做的:

// Get the system property store (type = sys)
    val sysPropsStore = ConfigStoreOptions().setType("sys")
    // Add system property store to the config retriever options
    val options = ConfigRetrieverOptions().addStore(sysPropsStore)
    // And create a ConfigRetriever
    val retriever = ConfigRetriever.create(vertx, options)

    // Set the default port
    var httpPort: Int = 8080

    retriever.getConfig { ar ->
        if (ar.failed()) {
            // Failed to retrieve the configuration
        } else {
            val config = ar.result()

            if (config.containsKey("http.port")) 
                httpPort = config.getInteger("http.port")
        }
    }

相关问题