maven打包jar

277 阅读2分钟

maven打包jar

  1. 使用到的maven插件
    <plugins>
        <!--执行jar插件-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <archive>
                        <manifest>
                            <!-- 项目启动类 -->
                            <mainClass>Main</mainClass>
                            <!-- 依赖的jar的目录前缀,classpath,可自定义,用来查找依赖jar的位置 -->
                            <classpathPrefix>../lib</classpathPrefix>
                            <!--在MANIFEST.MF中添加属性 Class-Path-->
                            <addClasspath>true</addClasspath>
                        </manifest>
                    </archive>
                    <!-- 项目启动jar包排除目录,在打包时取得都是target/classes 下的文件-->
                    <excludes>
                        <exclude>bin/**</exclude>
                        <exclude>config/**</exclude>
                        <exclude>logs/**</exclude>
                    </excludes>
                </configuration>
            </plugin>
            <!--springboot 打包插件-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <layout>ZIP</layout>
                    <includes>
                        <!-- 项目启动jar包中排除依赖包 -->
                        <include>
                            <groupId>non-exists</groupId>
                            <artifactId>non-exists</artifactId>
                        </include>
                    </includes>
                </configuration>
            </plugin>

            <!--将项目依赖的包重新输出到指定文件中-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>3.1.0</version>
                <executions>
                    <execution>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <<!--指定目录-->
                            <outputDirectory>target/lib</outputDirectory>
                            <overWriteReleases>false</overWriteReleases>
                            <overWriteSnapshots>false</overWriteSnapshots>
                            <overWriteIfNewer>true</overWriteIfNewer>
                            <includeScope>compile</includeScope>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.1.0</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>

            <!-- 打包时跳过测试 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.1</version>
                <configuration>
                    <skipTests>true</skipTests>
                </configuration>
            </plugin>

            <!-- 最终打包插件 -->
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <descriptors>
                        <!--打包配置详情配置文件-->
                        <descriptor>src/main/assembly/assembly.xml</descriptor>
                    </descriptors>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

        </plugins>

  1. maven-assembly-plugin 配置(src/main/assembly/assembly.xml)
  <?xml version="1.0" encoding="UTF-8"?>
  <assembly xmlns="http://maven.apache.org/ASSEMBLY/2.1.0"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.1.0 http://maven.apache.org/xsd/assembly-2.1.0.xsd">
      <!-- 可自定义,这里指定的是项目环境 -->
      <!-- spring-boot-assembly-local-1.0.RELEASE.tar.gz  -->
      <id>${profileActive}-${project.version}</id>

      <!-- 打包的类型,如果有N个,将会打N个类型的包 -->
      <formats>
          <format>tar.gz</format>
          <format>zip</format>
      </formats>

      <includeBaseDirectory>true</includeBaseDirectory>

      <fileSets>
          <!--
              0755->即用户具有读/写/执行权限,组用户和其它用户具有读写权限;
              0644->即用户具有读写权限,组用户和其它用户具有只读权限;
          -->
          <!-- 将target/classes/bin目录下的所有文件输出到打包后的bin目录中 -->
          <fileSet>
              <directory>${build.outputDirectory}/bin</directory>
              <outputDirectory>bin</outputDirectory>
              <fileMode>0755</fileMode>
          </fileSet>

          <!-- 指定输出target/classes中的配置文件到config目录中 -->
          <fileSet>
              <directory>${build.outputDirectory}/config</directory>
              <outputDirectory>config</outputDirectory>
              <fileMode>0644</fileMode>
          </fileSet>

          <!-- 指定输出target/classes中的配置文件到config目录中 -->
          <fileSet>
              <directory>${build.outputDirectory}/logs</directory>
              <outputDirectory>logs</outputDirectory>
              <fileMode>0644</fileMode>
          </fileSet>

          <!-- 将第三方依赖打包到lib目录中,插件 maven-dependency-plugin 所提取出的jar -->
          <fileSet>
              <directory>${build.directory}/lib</directory>
              <outputDirectory>lib</outputDirectory>
              <fileMode>0755</fileMode>
          </fileSet>

          <!-- 将项目启动jar打包到boot目录中 -->
          <fileSet>
              <directory>${build.directory}</directory>
              <outputDirectory>boot</outputDirectory>
              <fileMode>0755</fileMode>
              <includes>
                  <include>${project.build.finalName}.jar</include>
              </includes>
          </fileSet>

          <!-- 包含根目录下的文件 -->
          <fileSet>
              <directory>${basedir}</directory>
              <includes>
                  <include>NOTICE</include>
                  <include>LICENSE</include>
                  <include>*.md</include>
              </includes>
          </fileSet>
      </fileSets>
  </assembly>
  1. 执行脚本(src/bin)
    1. start.sh
        #! /bin/sh
    
        #======================================================================
        # 项目启动shell脚本
        # boot目录: spring boot jar包
        # config目录: 配置文件目录
        # logs目录: 项目运行日志目录
        # logs/startup.log: 记录启动日志
        # logs/back目录: 项目运行日志备份目录
        # nohup后台运行
        #======================================================================
    
        # 项目名称,该配置在pom.xml中属性,在执行resource时被替换,需要<filtering>true</filtering>
        APPLICATION="@project.name@"
    
        # 项目启动jar包名称
        APPLICATION_JAR="@build.finalName@.jar"
    
        # bin目录绝对路径
        BIN_PATH=$(cd `dirname $0`; pwd)
        # 进入bin目录
        cd `dirname $0`
        # 返回到上一级项目根目录路径,config以及一些其他文件都在上级根目录下
        cd ..
        # 打印项目根目录绝对路径
        # `pwd` 执行系统命令并获得结果
        BASE_PATH=`pwd`
    
        # 外部配置文件绝对目录,如果是目录需要/结尾,也可以直接指定文件
        # 如果指定的是目录,spring则会读取目录中的所有配置文件,如果配置文件目录相对当前所在目录满足 file:./,file:./config/,则该配置可不配
        CONFIG_DIR=${BASE_PATH}"/config/"
    
        # 项目日志输出绝对路径
        LOG_DIR=${BASE_PATH}"/logs"
        LOG_FILE="${APPLICATION}.log"
        LOG_PATH="${LOG_DIR}/${LOG_FILE}"
        # 日志备份目录
        LOG_BACK_DIR="${LOG_DIR}/back/"
    
        # 项目启动日志输出绝对路径
        LOG_STARTUP_PATH="${LOG_DIR}/startup.log"
    
        # 当前时间
        NOW=`date +'%Y-%m-%m-%H-%M-%S'`
        NOW_PRETTY=`date +'%Y-%m-%m %H:%M:%S'`
    
        # 启动日志
        STARTUP_LOG="================================================ ${NOW_PRETTY} ================================================\n"
    
        # 如果logs文件夹不存在,则创建文件夹
        if [[ ! -d "${LOG_DIR}" ]]; then
          mkdir "${LOG_DIR}"
        fi
    
        # 如果logs/back文件夹不存在,则创建文件夹
        if [[ ! -d "${LOG_BACK_DIR}" ]]; then
          mkdir "${LOG_BACK_DIR}"
        fi
    
        # 如果项目运行日志存在,则重命名备份
        if [[ -f "${LOG_PATH}" ]]; then
            mv ${LOG_PATH} "${LOG_BACK_DIR}/${APPLICATION}_back_${NOW}.log"
        fi
    
        # 创建新的项目运行日志
        echo "" > ${LOG_PATH}
    
        # 如果项目启动日志不存在,则创建,否则追加
        #echo "${STARTUP_LOG}" >> ${LOG_STARTUP_PATH}
    
        #==========================================================================================
        # JVM Configuration
        # -Xmx256m:设置JVM最大可用内存为256m,根据项目实际情况而定,建议最小和最大设置成一样。
        # -Xms256m:设置JVM初始内存。此值可以设置与-Xmx相同,以避免每次垃圾回收完成后JVM重新分配内存
        # -Xmn512m:设置年轻代大小为512m。整个JVM内存大小=年轻代大小 + 年老代大小 + 持久代大小。
        #          持久代一般固定大小为64m,所以增大年轻代,将会减小年老代大小。此值对系统性能影响较大,Sun官方推荐配置为整个堆的3/8
        # -XX:MetaspaceSize=64m:存储class的内存大小,该值越大触发Metaspace GC的时机就越晚
        # -XX:MaxMetaspaceSize=320m:限制Metaspace增长的上限,防止因为某些情况导致Metaspace无限的使用本地内存,影响到其他程序
        # -XX:-OmitStackTraceInFastThrow:解决重复异常不打印堆栈信息问题
        #==========================================================================================
        JAVA_OPT="-server -Xms256m -Xmx256m -Xmn512m -XX:MetaspaceSize=64m -XX:MaxMetaspaceSize=256m"
        JAVA_OPT="${JAVA_OPT} -XX:-OmitStackTraceInFastThrow"
    
        #=======================================================
        # 将命令启动相关日志追加到日志文件
        #=======================================================
    
        # 输出项目名称
        STARTUP_LOG="${STARTUP_LOG}application name: ${APPLICATION}\n"
        # 输出jar包名称
        STARTUP_LOG="${STARTUP_LOG}application jar  name: ${APPLICATION_JAR}\n"
        # 输出项目根目录
        STARTUP_LOG="${STARTUP_LOG}application root path: ${BASE_PATH}\n"
        # 输出项目bin路径
        STARTUP_LOG="${STARTUP_LOG}application bin  path: ${BIN_PATH}\n"
        # 输出项目config路径
        STARTUP_LOG="${STARTUP_LOG}application config path: ${CONFIG_DIR}\n"
        # 打印日志路径
        STARTUP_LOG="${STARTUP_LOG}application log  path: ${LOG_PATH}\n"
        # 打印JVM配置
        STARTUP_LOG="${STARTUP_LOG}application JAVA_OPT : ${JAVA_OPT}\n"
        
        # 打印启动命令
        STARTUP_LOG="${STARTUP_LOG}application startup command: nohup java ${JAVA_OPT} -jar ${BASE_PATH}/boot/${APPLICATION_JAR} --spring.config.location=${CONFIG_DIR} > ${LOG_PATH} 2>&1 &\n"
    
        #======================================================================
        # 执行启动命令:后台启动项目,并将日志输出到项目根目录下的logs文件夹下
        #======================================================================
        nohup java ${JAVA_OPT} -jar ${BASE_PATH}/boot/${APPLICATION_JAR} --spring.config.location=${CONFIG_DIR} > ${LOG_PATH} 2>&1 &
    
        # 进程ID
        PID=$(ps -ef | grep "${APPLICATION_JAR}" | grep -v grep | awk '{ print $2 }')
        STARTUP_LOG="${STARTUP_LOG}application pid: ${PID}\n"
    
        # 启动日志追加到启动日志文件中
        echo -e ${STARTUP_LOG} >> ${LOG_STARTUP_PATH}
        # 打印启动日志
        echo -e ${STARTUP_LOG}
    
        # 打印项目日志
        tail -f ${LOG_PATH}
    
    
    1. stop.sh
    #! /bin/sh
    
    #======================================================================
    # 项目停服shell脚本
    # 通过项目名称查找到PID
    # 然后kill -9 pid
    #
    #======================================================================
    
    # 项目名称
    APPLICATION="@project.name@"
    
    # 项目启动jar包名称
    APPLICATION_JAR="@build.finalName@.jar"
    
    PID=$(ps -ef | grep "${APPLICATION_JAR}" | grep -v grep | awk '{ print $2 }')
    if [[ -z "$PID" ]]
    then
        echo ${APPLICATION} is already stopped
    else
        echo kill  ${PID}
        ## 执行kill,在此不直接杀死进程,因为项目里可能有一些hook需要执行
        kill $pid
        sleep 5s
        is_exist
        ##如果进程在5s后还未被杀死,此时可能会有问题,则强制杀死
        if [ $? -eq "0" ]; then
            kill -9 $pid
        fi
        echo ${APPLICATION} stopped successfully
    fi
    
    1. restart.sh
        #! /bin/sh
    
        #======================================================================
        # 项目重启shell脚本
        # 先调用stop.sh停服
        # 然后调用start.sh启动服务
        #
        #======================================================================
    
        # 项目名称
        APPLICATION="@project.name@"
    
        # 项目启动jar包名称
        APPLICATION_JAR="@build.finalName@.jar"
    
        # 停服
        echo stop ${APPLICATION} Application...
        sh stop.sh
    
        # 启动服务
        echo start ${APPLICATION} Application...
        sh start.sh