12.5 使用Cargo实现自动化部署
Cargo是一组帮助用户操作Web容器的工具,它能够帮助用户实现自动化部署,而且它几乎支持所有的Web容器,如Tomcat、JBoss、Jetty和Glassfish等。Cargo通过cargo-maven2-plugin提供了Maven集成,Maven用户可以使用该插件将Web项目部署到Web容器中。虽然cargo-maven2-plugin和jetty-maven-plugin的功能看起来很相似,但它们的目的是不同的,jetty-maven-plugin主要用来帮助日常的快速开发和测试,而cargo-maven2-plugin主要服务于自动化部署。例如专门的测试人员只需要一条简单的Maven命令,就可以构建项目并部署到Web容器中,然后进行功能测试。本节以Tomcat 6为例,介绍如何自动化地将Web应用部署至本地或远程Web容器中。
12.5.1 部署至本地Web容器
Cargo支持两种本地部署的方式,分别为standalone模式和existing模式。在standalone模式中,Cargo会从Web容器的安装目录复制一份配置到用户指定的目录,然后在此基础上部署应用,每次重新构建的时候,这个目录都会被清空,所有配置被重新生成。而在existing模式中,用户需要指定现有的Web容器配置目录,然后Cargo会直接使用这些配置并将应用部署到其对应的位置。代码清单12-14展示了standalone模式的配置样例。
代码清单12-14 使用standalone模式部署应用至本地Web容器
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>1.0</version>
<configuration>
<container>
<containerId>tomcat6x</containerId>
<home>D:\cmd\apache-tomcat-6.0.29</home>
</container>
<configuration>
<type>standalone</type>
<home>${project.build.directory}/tomcat6x</home>
</configuration>
</configuration>
</plugin>
cargo-maven2-plugin的groupId是org.codehaus.cargo,这不属于官方的两个Maven插件groupId,因此用户需要将其添加到settings.xml的pluginGroup元素中以方便命令行调用。
上述cargo-maven2-plugin的具体配置包括了container和configuration两个元素,configu-ration的子元素type表示部署的模式(这里是standalone)。与之对应的,configuration的home子元素表示复制容器配置到什么位置,这里的值为${project.build.directory}/tomcat6x,表示构建输出目录,即target/下的tomcat6x子目录。container元素下的containerId表示容器的类型,home元素表示容器的安装目录。基于该配置,Cargo会从D:\cmd\apache-tomcat-6.0.29目录下复制配置到当前项目的target/tomcat6x/目录下。
现在,要让Cargo启动Tomcat并部署应用,只需要运行:
$mvn cargo:start
以account-web为例,现在就可以直接访问地址的账户注册页面[1]了。
默认情况下,Cargo会让Web容器监听8080端口。可以通过修改Cargo的cargo.servlet.port属性来改变这一配置,如代码清单12-15所示。
代码清单12-15 更改Cargo的Servlet监听端口
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>1.0</version>
<configuration>
<container>
<containerId>tomcat6x</containerId>
<home>D:\cmd\apache-tomcat-6.0.29</home>
</container>
<configuration>
<type>standalone</type>
<home>${project.build.directory}/tomcat6x</home>
<properties>
<cargo.servlet.port>8081</cargo.servlet.port>
</properties>
</configuration>
</configuration>
</plugin>
要将应用直接部署到现有的Web容器下,需要配置Cargo使用existing模式,如代码清单12-16所示。
代码清单12-16 使用existing模式部署应用至本地Web容器
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>1.0</version>
<configuration>
<container>
<containerId>tomcat6x</containerId>
<home>D:\cmd\apache-tomcat-6.0.29</home>
</container>
<configuration>
<type>existing</type>
<home>D:\cmd\apache-tomcat-6.0.29</home>
</configuration>
</configuration>
</plugin>
上述代码中configuration元素的type子元素的值为existing,而对应的home子元素表示现有的Web容器目录,基于该配置运行mvn cargo:start之后,便能够在Tomcat的webapps子目录看到被部署的Maven项目。
[1]地址为http:localhost:8080/account-web-1.0.0-SNAPSHOT/signup.jsp。