Java 从命令行启动jar时从命令行获取配置属性
我尝试在本地和Heroku上启动vert.x示例(使用Procfile):Java 从命令行启动jar时从命令行获取配置属性,java,heroku,vert.x,Java,Heroku,Vert.x,我尝试在本地和Heroku上启动vert.x示例(使用Procfile): java-Dhttp.port=$port-jarmyapp.jar 我的经验是,属性(http.port)没有设置,因此我的程序无法访问 使用System.getenv()读取端口环境变量是可行的,但不是“最佳实践” 为什么??我能做什么? Ove正如@dpr所指出的那样,ConfigRetriever是一条路要走 以下是我最后做的: // Get the system property store (type = s
java-Dhttp.port=$port-jarmyapp.jar
我的经验是,属性(http.port)没有设置,因此我的程序无法访问
使用System.getenv()读取端口环境变量是可行的,但不是“最佳实践”
为什么??我能做什么?
Ove正如@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")
}
}
最好的方法是定义一个json文件,并在其中添加所有与配置相关的vertx 启动应用程序时将config.json作为参数传递 以下是一个例子: Config.json文件 运行应用程序时将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
}
}
public类MainVerticle扩展了AbstractVerticle{
@凌驾
public void start(Future startFuture)引发异常{
JsonObject data=this.config();
//从JsonObject读取端口和其他与配置相关的内容
}
}
我希望这将帮助您:)您如何尝试获取
http.port
的值?使用System.getProperties().get(“http.port”)
或一些vert.x内部魔法?我使用的是vert.x魔法:config().getInteger(“http.port”,8080)我对vert.x不太了解,但从这个页面()我想您需要使用sys
类型:def sysPropsStore=[类型:“sys”]
并使用此选项查找配置选项。您可能可以使用默认的配置检索器,因为它还应该包含系统属性。为什么使用system.getenv()
不是最佳做法?这是获取$PORT
?@codefinger值的最权威的方法,因为您必须将设置作为OS环境变量提供。如果使用的是配置检索器,则可以将设置作为系统属性、属性文件或环境变量提供。这可能对不同的部署场景有用。它可能有用,而且我知道这种方法。问题是Heroku分配了一个随机端口。这是在您的垂直start()
,还是在哪里?
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
}
}