maven-assembly-plugin插件打包 jar、tar.gz
使用?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/java server_home=`dirname $0`/.. class_lib=$server_home/lib log_home=$server_home/logs/example/ log_out=$log_home/stdout.log log_err=$log_home/stderr.logif [ ! -d $log_home ]; thenmkdir -p $log_home fi#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簡單的打包方式介紹完畢!
整個項目結構如下:
總結
以上是生活随笔為你收集整理的maven-assembly-plugin插件打包 jar、tar.gz的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Bitmap之compress图片压缩
- 下一篇: Guice进阶之整合mybatis和dr