Springboot 瘦身打包

5 篇文章 0 订阅
4 篇文章 0 订阅

分离 lib 依赖和资源文件

在这里插入图片描述
在实际生产过程中,常常会遇到资源打包文件太大,在部署的时候很不方便,传统的打包方式会将所有的文件(jar 和 资源配置文件)都打包在了一个 jar 文件中,这样后期在修改配置信息的时候,相当的不方便。

因此,如何将项目本身的 jar 文件和依赖 jar 文件分离,并把资源文件也分离出来,分别独立成自己的文件目录是很有必要的。

一、传统打包方式
传统的打包方式在 pom.xml 中只需要在 build 插件中配置spring-boot-maven-plugin即可:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

打包出来的 jar 包是下面这样的,项目生成了target文件目录,里面打包好了一个完整的 jar 文件,直接使用:java -jar king-0.0.1-SNAPSHOT.jar就能运行了。
在这里插入图片描述
打成完整的 jar 包

将 jar 包解压开,会得到下面的目录结构:
在这里插入图片描述
打成完整 jar 包的内部结构

注意在META-INF文件目录中存在MANIFEST.MF文件,里面记录了启动类Start-Class 、依赖类Spring-Boot-Lib等信息。

运行 jar 包的时候,首先启动的是启动类,并依赖BOOT-INF/lib/文件目录中的 jar 文件。

二、springboot 打包 lib 和资源文件分离
现在有如下的打包需求:

项目自身 jar 文件打包在 zip 包根目录下,其他所有依赖包打包在lib文件夹下,资源文件全部打包在resources文件目录下,项目运行的脚本文件打包在bin文件目录下。
在这里插入图片描述
在pom.xml配置:

<build>
    <plugins>
        <!--打包jar -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <!--不打包资源文件 -->
                <excludes>
                    <exclude>bin/**</exclude>
                    <exclude>config/**</exclude>
                    <exclude>static/**</exclude>
                    <exclude>templates/**</exclude>
                    <exclude>*.yml</exclude>
                </excludes>
                <!-- 
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        // MANIFEST.MF 中 Class-Path 加入前缀,不需要配置,在外部命令行指定                         
                        <classpathPrefix>lib/</classpathPrefix> 
                        // jar包不包含唯一版本标识 
                        <useUniqueVersions>false</useUniqueVersions> 
`                       // 指定入口类,如果程序里只有一个main方法就建议不要手动配置 
                        <mainClass>org.woodwhale.king.KingApplication</mainClass>
                        </manifest>
                    <manifestEntries> 
                    // MANIFEST.MF 中 Class-Path 加入资源文件目录,不需要配置,在外部命令行指
                    <Class-Path>./resources/</Class-Path> 
                    </manifestEntries>
                </archive>
                -->

                <!-- 
                    生成到 target 目录下,
                    也可以放到指定目录,例如: ${project.build.directory}/boot
                -->
                <outputDirectory>${project.build.directory}</outputDirectory>
            </configuration>
        </plugin>

        <!--拷贝依赖 copy-dependencies -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                           <outputDirectory>${project.build.directory}/lib</outputDirectory>
                        <overWriteReleases>false</overWriteReleases>
                        <overWriteSnapshots>false</overWriteSnapshots>
                        <overWriteIfNewer>true</overWriteIfNewer>
                    </configuration>
                </execution>
            </executions>
        </plugin>

        <!--拷贝资源文件 copy-resources -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <executions>
                <execution>
                    <id>copy-resources</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy-resources</goal>
                    </goals>
                    <configuration>
                        <encoding>UTF-8</encoding>
                        <resources>
                            <resource>
                                <directory>src/main/resources</directory>
                            </resource>
                        </resources>
                        <outputDirectory>${project.build.directory}/resources</outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>

        <!-- 
            spring boot repackage,
            依赖 maven-jar-plugin 打包的jar包 
            重新打包成 spring boot的jar包
        -->
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <!-- 包含本地 jar 依赖 -->
                <includeSystemScope>true</includeSystemScope>
                <!-- 重写包含依赖,包含不存在的依赖,jar里没有pom里的依赖 -->
                <includes>
                    <include>
                        <groupId>null</groupId>
                        <artifactId>null</artifactId>
                    </include>
                </includes>
                <layout>ZIP</layout>
                <!-- 使用外部配置文件,jar包里没有资源文件 -->
                <addResources>true</addResources>
                <outputDirectory>${project.build.directory}</outputDirectory>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                    <configuration>
                        <!-- 
                        配置jar包特殊标识 配置后,保留原文件,
                        生成新文件 *-run.jar 配置jar包特殊标识 不配置, 
                        原文件命名为 *.jar.original,生成新文件 *.jar
                        -->
                        <classifier>run</classifier>
                    </configuration>
                </execution>
            </executions>
        </plugin>

        <!-- 打包发布时,跳过单元测试 -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <skipTests>true</skipTests>
            </configuration>
        </plugin>

        <!-- 使用assembly打zip包 -->
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
                <appendAssemblyId>false</appendAssemblyId>
                <descriptors>
                    <!-- assembly配置文件位置 -->
                    <descriptor>assembly.xml</descriptor>
                </descriptors>
            </configuration>
            <executions>
                <execution>
                    <id>make-assembly</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

注意:在spring-boot-maven-plugin中配置了包含本地jar依赖的配置<includeSystemScope>true</includeSystemScope>

在项目根目录下存在放置assembly.xml配置:

<assembly
    xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
    <id>${project.artifactId}</id>
    <formats>
        <format>zip</format>
    </formats>
    <!-- 压缩包下是否生成和项目名相同的根目录 -->
    <includeBaseDirectory>false</includeBaseDirectory>
    <baseDirectory>${project.artifactId}-${project.version}</baseDirectory>

    <fileSets>
        <fileSet>
            <directory>${project.build.directory}</directory>
            <outputDirectory></outputDirectory> 
            <includes>
                <include>${artifact.artifactId}-${artifact.version}.jar</include>
            </includes>
        </fileSet>
        <fileSet>  
            <directory>src/main/resources</directory>
            <outputDirectory>${file.separator}resources</outputDirectory>
        </fileSet>
        <fileSet>  
            <directory>bin/</directory>
            <outputDirectory>${file.separator}bin</outputDirectory>
        </fileSet>
        <fileSet>  
            <directory>lib/</directory>
            <outputDirectory>${file.separator}lib</outputDirectory>
        </fileSet>
    </fileSets>

    <!-- 使用项目的artifact,第三方 jar 打包进zip文件的 lib 目录 -->
    <dependencySets>
        <dependencySet>
            <useProjectArtifact>true</useProjectArtifact>
            <outputDirectory>lib</outputDirectory>
            <scope>runtime</scope>
            <includes>
                <include>*:*</include>
            </includes>
            <excludes>
                <exclude>${groupId}:${artifactId}</exclude>
                <exclude>org.springframework.boot:spring-boot-devtools</exclude>
            </excludes>
        </dependencySet>
    </dependencySets>
</assembly>

bin脚本文件目录中放置脚本文件和配置文件:

配置文件用于指定 jar 的名称及版本信息

ARTIFACTID=king
VERSION=0.0.1

windows 脚本start.bat文件:

ECHO off

ECHO "checking config.ini..."

SET ROOT=%~dp0
SET CONFIG_FILE=%ROOT%config.ini
REM **从配置文件中读取内容**
FOR /F "tokens=1,2 delims==" %%i IN (%CONFIG_FILE%) DO (
 SET %%i=%%j
)
SET APP_NAME=%ARTIFACTID%-%VERSION%

IF "%APP_NAME%" == "" (
    ECHO "this config.ini is not exist,please check this config file."  
    GOTO End
) ELSE (
    ECHO "checking JAVA_HOME config from checking config.ini..."
    GOTO OkPath
)

:OkPath
echo "check java_home..."
if not "%JAVA_HOME%" == "" GOTO OkJHome

:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" GOTO Runserver

:Runserver
SET JAR_NAME=%APP_NAME%.jar
SET APP_CONFIG=-Dloader.path=.,resources,lib

ECHO "111:%RUN_JAVA%"
ECHO "Starting the %JAR_NAME%"

ECHO "%JAVA_HOME%\bin\java -Xms512m -Xmx512m -jar %APP_CONFIG% %JAR_NAME%"
CD ..
%JAVA_HOME%\bin\java.exe -Xms512m -Xmx512m -jar %APP_CONFIG% %JAR_NAME%
GOTO End

:End
PAUSE

脚本解释:最为关键的就是运行jar 文件的时候携带-Dloader.path=.,resources,lib

linux 脚本startup.sh文件:

#!/bin/sh

## java env
export JAVA_HOME=/usr/java/jdk1.8.0_162
API_NAME=./king-0.0.1.jar

export JRE_HOME=JAVA_HOME/jre
API_CONFIG=.,resources,lib
JAR_NAME=$API_NAME.jar
PID=$API_NAME.pid

usage() {
    echo "Usage: sh startup.sh [start|stop|restart|status]"
    exit 1
}

is_exist(){
  pid=`ps -ef|grep $JAR_NAME|grep -v grep|awk '{print $2}' `
  if [ -z "${pid}" ]; then
   return 1
  else
    return 0
  fi
}

start(){
  is_exist
  if [ $? -eq "0" ]; then 
    echo ">>> ${JAR_NAME} is already running PID=${pid} <<<" 
  else 
    nohup $JRE_HOME/bin/java -Xms256m -Xmx512m -jar -Dloader.path=$API_CONFIG $JAR_NAME >/dev/null 2>&1 &
    echo $! > $PID
    echo ">>> start $JAR_NAME successed PID=$! <<<" 
   fi
  }

stop(){
  #is_exist
  pidf=$(cat $PID)
  #echo "$pidf"  
  echo ">>> api PID = $pidf begin kill $pidf <<<"
  kill $pidf
  rm -rf $PID
  sleep 2
  is_exist
  if [ $? -eq "0" ]; then 
    echo ">>> api 2 PID = $pid begin kill -9 $pid  <<<"
    kill -9  $pid
    sleep 2
    echo ">>> $JAR_NAME process stopped <<<"  
  else
    echo ">>> ${JAR_NAME} is not running <<<"
  fi  
}

status(){
  is_exist
  if [ $? -eq "0" ]; then
    echo ">>> ${JAR_NAME} is running PID is ${pid} <<<"
  else
    echo ">>> ${JAR_NAME} is not running <<<"
  fi
}

restart(){
  stop
  start
}

case "$1" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  "restart")
    restart
    ;;
  *)
    usage
    ;;
esac
exit 0

shell 脚本里需要配置JAVA_HOME路径和 jar 文件名即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值