使用参数部署* .war文件

时间:2017-10-25 08:23:42

标签: java tomcat config war

我有REST API的web项目。我想在tomcat服务器上部署它的5个副本。例如:
test1.war =>网址:http://localhost:8080/test1/api
test2.war =>网址:http://localhost:8080/test2/api
test3.war =>网址:http://localhost:8080/test3/api
...
问题是每个war文件应该使用不同的配置文件。我知道我可以使用export CATALINA_OPTs="Dparam1=/usr/config1.txt"设置env变量。然后我需要更改每个war文件中的源代码,以便为test1.war读取param1,为test2.war读取param2。但每个war文件应该是相同的(只有不同​​的名称)。从理论上讲,完美的解决方案是这样的:

    deploy test1.war -conf <path1>
    deploy test2.war -conf <path2>
    deploy test3.war -conf <path3>


是否可以在tomcat中执行此操作?这样做有其他选择吗?

1 个答案:

答案 0 :(得分:1)

我决定在运行时为app获取适当的配置文件。

1)使用以下代码获取当前正在运行的MainApp.class(例如 warname.war )文件的路径:

String path = MainApp.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = java.net.URLDecoder.decode(path, "UTF-8");
// decodedPath - "D:/apache-tomcat-7.0.81/apache-tomcat-7.0.81/webapps/warname/WEB-INF/classes/com/gieseckedevrient/rsp/servertester/MainApp.class"


2)解析此解码路径,以便只获得&#34; warname &#34;:

String parentName = "";
java.io.File parentFile = null;
while (!"WEB-INF".equals(parentName)) {
  File file = new File(decodedPath);
  parentFile = file.getParentFile();
  parentName = parentFile.getName();
  decodedPath = parentFile.getAbsolutePath();               
  }
String realWarName = parentFile.getParentFile().getName();


3)创建文件&#34; setenv.bat&#34;在TOMCAT_HOME} / bin /中插入此代码( warname.config.file 用于 warname.war warname2.config.file warname2.war ):

set CATALINA_OPTS=-Dwarname.config.file=D:\app.properties -Dwarname2.config.file=D:\app2.properties


4)使用以下代码读取相应的env变量:

String configFile = System.getProperty(realWarName + ".config.file");
// configFile - "D:\app.properties" for warname.war
// configFile - "D:\app2.properties" for warname2.war