瘦身SpringBoot:优化项目打包大小的方法
- 1、打jar包的痛点
- 2、瘦身思路
- 3、开始打包
- 4、如何启动项目
1、打jar包的痛点
现有的应用开发中,不论是单体架构、微服务架构,如果项目采用的是 springboot、springcloud 来作为底层框架,打包时最终都会以jar包的方式打包、部署。这是就会面临一个问题,就是 jar 包非常大,单体应用还好,但是如果是微服务就非常痛苦,几十个微服务就要拆分打包几十个 jar 包,每个 jar 包都很大(几百M),合起来就好几个 GB,非常占用空间。
2、瘦身思路
在以往的打包过程当中,会将自己编写的代码以及我们所使用到的依赖进行整合打到同一个jar包当中,而在实际的项目开发当中,只是对一个java文件进行修改,但是重新打包还是会打对应的依赖进去,整个包的体积也变大了,因此这里就想将依赖进行抽离出来单独打包,如下图所示
3、开始打包
首先我们先查看以往打包,这里我简单提供了一个微服务项目进行打包,可以看到也有个50兆左右的大小
在项目的pom当中添加以下配置:对启动类进行自定义配置,其余配置不需要大改。
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.1</version>
<configuration>
<!--启动类配置-->
<mainClass>com.lq.LqAirTicketApplication</mainClass>
<!--解决windows命令行窗口中文乱码-->
<jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
<layout>ZIP</layout>
<!--配置需要打包进项目的jar-->
<includes>
<!--这里是填写需要包含进去的jar,
必须项目中的某些模块,会经常变动,那么就应该将其坐标写进来
如果没有则non-exists ,表示不打包依赖
-->
<include>
<groupId>non-exists</groupId>
<artifactId>non-exists</artifactId>
</include>
</includes>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- 此插件用于将依赖包抽出-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.1.1</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<!--是否排除传递性-->
<excludeTransitive>false</excludeTransitive>
<!--是否去掉 jar 包版本信息-->
<stripVersion>false</stripVersion>
<!--包含范围-->
<includeScope>runtime</includeScope>
</configuration>
</execution>
</executions>
</plugin>
直接重新加载maven进行打包,打包之后查看打包效果,可以看到依赖都打包到这个lib文件夹当中,而我们自己所编写的代码所打成的jar包体积变小了很多,
4、如何启动项目
由于打包之后将依赖从jar包当中抽离出来了,所以这里不能直接用java -jar启动,而是需要指定对应的依赖进行启动项目
java -jar -Dloader.path="./lib" xxx.jar