现在使用 Jenkins 自动化部署项目有这样一个问题,那就是项目使用到的 jar 包比较多,这就导致每次将 war 包上传到服务器上的时间就比较长。今天无意间看到一个方法可以大幅减少 war 包大小,提升效率。

方法很简单就是将第三方 jar 包直接放到 tomcat 的 lib 目录下,而不是放在项目的 lib 文件夹下,这样就可以让一个 war 包显著的缩小体积,并且不影响项目本身。

tomcat_home/lib 下新建自定义jar包文件,比如 jsdoctor,导入项目所需其他jar包(以后有新增的话,单独再导一次)
修改 tomcat_home/conf/catalina.propertiesshared.loader 后面加上 ${catalina.base}/lib/jsdoctor/*.jar

下面是一段我自己编写的 shell 脚本,目的是去除 war 包中的第三方 jar 包并且保留项目自己模块的 jar。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 将 core 和 common 包移动到临时位置
mv /root/.jenkins/workspace/jsdoctor/jsdoctor-platform-admin/target/jsdoctor-platform-admin-1.0-SNAPSHOT/WEB-INF/lib/jsdoctor-common-1.0-SNAPSHOT.jar /root/.jenkins/workspace/jsdoctor/jsdoctor-platform-admin/target

mv /root/.jenkins/workspace/jsdoctor/jsdoctor-platform-admin/target/jsdoctor-platform-admin-1.0-SNAPSHOT/WEB-INF/lib/jsdoctor-core-1.0-SNAPSHOT.jar /root/.jenkins/workspace/jsdoctor/jsdoctor-platform-admin/target

# 删除 lib 下所有文件
rm -rf /root/.jenkins/workspace/jsdoctor/jsdoctor-platform-admin/target/jsdoctor-platform-admin-1.0-SNAPSHOT/WEB-INF/lib/*

# 删除生成的 war 包
rm -rf /root/.jenkins/workspace/jsdoctor/jsdoctor-platform-admin/target/jsdoctor-platform-admin.war

# 将 core 和 common 包移动回来
mv /root/.jenkins/workspace/jsdoctor/jsdoctor-platform-admin/target/jsdoctor-common-1.0-SNAPSHOT.jar /root/.jenkins/workspace/jsdoctor/jsdoctor-platform-admin/target/jsdoctor-platform-admin-1.0-SNAPSHOT/WEB-INF/lib/

mv /root/.jenkins/workspace/jsdoctor/jsdoctor-platform-admin/target/jsdoctor-core-1.0-SNAPSHOT.jar /root/.jenkins/workspace/jsdoctor/jsdoctor-platform-admin/target/jsdoctor-platform-admin-1.0-SNAPSHOT/WEB-INF/lib/

# 打包
cd /root/.jenkins/workspace/jsdoctor/jsdoctor-platform-admin/target/jsdoctor-platform-admin-1.0-SNAPSHOT
zip -q -r jsdoctor-platform-admin.war ./*
mv jsdoctor-platform-admin.war /root/.jenkins/workspace/jsdoctor/jsdoctor-platform-admin/target