使用maven-assembly-plugin 插件可以将我们的java application(java应用程序)打成可执行jar,下面简要介绍一下使用maven-assembly-plugin打包可执行jar和tar.gz。
前面我们已经介绍过maven 多环境打包配置;此处不再介绍
可执行jar包配置
打开pom.xml,在bulid->plugins中加入插件配置:
<plugin><artifactId>maven-assembly-plugin</artifactId><version>2.6</version><configuration><archive><manifest><mainClass>com.test.example</mainClass></manifest></archive><descriptorRefs><descriptorRef>jar-with-dependencies</descriptorRef></descriptorRefs></configuration><executions><execution><id>make-assembly</id> <!-- this is used for inheritance merges --><phase>package</phase> <!-- bind to the packaging phase --><goals><goal>single</goal></goals></execution></executions></plugin>
注意mainClass为主函数main所在的入口类
运行配置如下
运行后会在target目录下生成对应的jar,默认名称为xxx-1.0-SNAPSHOT-jar-with-dependencies.jar,直接java -jar 即可运行
tar.gz打包配置
以上我们成功了打包了一个可执行jar,它的关键就在于指定主函数的入口类即可;弊端就是对于一个应用我们只能指定一个主函数入口类,所以如果我们要启动多个进程就只能创建多个application了,这对于我来说是一件非常痛苦的事,所以为了解决一个项目中可以启动多个进程,我们可以将该类型应用打包成tar.gz(主要是为了在linux机器上运行),然后为每个入口类创建一个启动脚本,最后需要启动哪个应用就直接执行对应的脚本即可;
打开pom.xml配置更改为如下:
<!--linux 下执行 打包方式为 tar.gz--><plugin><artifactId>maven-assembly-plugin</artifactId><version>2.2</version><configuration><descriptors><descriptor>distribution.xml</descriptor></descriptors></configuration><executions><execution><id>make-assembly</id><phase>package</phase></execution></executions></plugin>
distribution.xml内容如下:
<assembly><id>dist</id><formats><format>tar.gz</format></formats><includeBaseDirectory>false</includeBaseDirectory><fileSets><fileSet><includes><include>README*</include><include>LICENSE*</include><include>NOTICE*</include></includes></fileSet><fileSet><directory>target/classes</directory><outputDirectory>classes</outputDirectory></fileSet><fileSet><directory>bin</directory><outputDirectory>bin</outputDirectory></fileSet></fileSets><dependencySets><dependencySet><outputDirectory>lib</outputDirectory><scope>runtime</scope></dependencySet></dependencySets></assembly>
shell脚本示例如下:
#!/bin/bashjava_bin=$JAVA_HOME/bin/javaserver_home=`dirname $0`/..class_lib=$server_home/liblog_home=$server_home/logs/example/log_out=$log_home/stdout.loglog_err=$log_home/stderr.logif [ ! -d $log_home ]; thenmkdir -p $log_homefi#if [[ -e $server_home/example.pid ]]; then# kill `cat $server_home/example.pid`#fijava_opts="-Xmx512m -Dfile.encoding=utf8 -cp :${class_lib}/*"$java_bin $java_opts com.test.example 1>>$log_out 2>>$log_err &echo $! > $server_home/example.pid
注:log_home 为日志目录,example.pid为进程id,com.test.example为主函数入口类
打包后的jar包如下:
最后将该文件发到linux下解压进入bin目录,执行相应脚本即可运行(sh example.sh),然后可以到logs下查看对应的日志信息
另外,你可以在同一个项目中编写另外N个程序,只需要创建多个shell启动脚本,每个脚本中指定对应的函数入口类以及对应的进程id和日志目录即可
至此maven-assembly-plugin简单的打包方式介绍完毕!
整个项目结构如下: