使用参数部署*.war文件

6
我有一个包含REST API的Web项目,想要在Tomcat服务器上部署5个副本。例如:
test1.war => URL: http://localhost:8080/test1/api
test2.war => URL: http://localhost:8080/test2/api
test3.war => URL: http://localhost:8080/test3/api
...
问题是每个war文件都应该使用不同的配置文件。我知道可以使用export CATALINA_OPTS="Dparam1=/usr/config1.txt"设置环境变量。然后我需要更改每个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
你可能也想在tomcat邮件列表中询问这个问题,看看是否有人知道。 - Zachary Craig
1个回答

3

我决定在运行时获取适当的应用程序配置文件。

1) 通过以下代码获取war(例如warname.war)文件中当前运行的MainApp.class的路径:

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) 解码该路径以仅获取 "warname" :

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) 在{TOMCAT_HOME}/bin/目录下创建文件"setenv.bat",并插入以下代码(warname.warwarname.config.filewarname2.warwarname2.config.file):

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


4) 使用以下代码读取适当的环境变量:

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

我目前正在尝试您的解决方案,它似乎有效,但我的第二个.war未能部署,因为bean名称已被第一个.war使用,所以我收到了InstanceAlreadyExistsException异常。您如何处理这种情况? - syd
我没有这样的异常。但我猜这个链接可以帮助 https://github.com/spring-cloud/spring-cloud-config/issues/118 - Maksym

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接