spring boot 分离打包

  |   0 评论   |   0 浏览

Spring Boot项目默认的会打包成单一的jar文件,但是有时候我们并不想让配置文件、依赖包都跟可执行文件打包到一起。这时候可以在pom.xml文件中进行配置,从而使资源文件、依赖包和可执行文件分离。pom.xml配置如下:

pom文件

<build>
        <plugins>
            <!-- 将相同groupId的依赖模块打包进来 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <configuration>
                    <createDependencyReducedPom>false</createDependencyReducedPom>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <!--为了把相同包名的打到一块-->
                        <!--<configuration>
                            <artifactSet>
                                <includes>
                                    <include>${project.groupId}:*:*</include>
                                </includes>
                            </artifactSet>
                        </configuration>-->
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <!--打包时去除第三方依赖-->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <layout>ZIP</layout>
                    <includes>
                        <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>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <!--target/lib是依赖jar包的输出目录,根据自己喜好配置-->
                            <outputDirectory>target/lib</outputDirectory>
                            <excludeTransitive>false</excludeTransitive>
                            <stripVersion>false</stripVersion>
                            <includeScope>runtime</includeScope>
                            <excludeGroupIds>${project.groupId}</excludeGroupIds>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.8</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <tasks>
                                <!-- 文件夹 -->
                                <copy todir="${project.build.directory}/build/conf" overwrite="true">
                                    <fileset dir="${basedir}/src/main/resources">
                                        <include name="**/*.*"/>
                                        <exclude name="mybatis/*/*.*"/>
                                    </fileset>
                                </copy>
                                <move todir="${project.build.directory}/build/lib">
                                    <fileset dir="target/lib"/>
                                </move>
                                <copy file="${project.build.directory}/${project.artifactId}-${project.version}.jar"
                                      tofile="${project.build.directory}/build/${project.artifactId}.jar" />

                                <fixcrlf srcdir="${basedir}/src/main/build/scripts" eol="unix"/>
                                <copy todir="${project.build.directory}/build/bin">
                                    <fileset dir="${basedir}/src/main/build/scripts">
                                        <include name="*.sh" />
                                        <include name="*.txt" />
                                        <include name="*.bat" />
                                    </fileset>
                                </copy>
                                <zip destfile='${project.build.directory}/build/${project.artifactId}.zip'>
                                    <zipfileset filemode="755" dir= '${project.build.directory}/build/' />
                                </zip>
                            </tasks>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

打包后

image.png

两种启动方式

  1. 使用脚本启动 打包后 cd到bin目录 执行./start.sh

1.1 在项目名称/src/main下创建build目录 再在build目录下创建scripts目录

image.png

1.2在项目名称/src/main/build/scripts创建 start.sh

#!/bin/bash

ENGINE=novel-front.jar
cd ../

#部署目路
DEPLOY_DIR=`pwd`
#获取到当前目录的名称
SERVER_NAME=`basename $DEPLOY_DIR`

#应用进程
PIDS=`ps -ef | grep java | grep "$ENGINE" |awk '{print $2}'`
#设置日志文件的输出目录
LOGS_DIR=$DEPLOY_DIR/logs
if [ ! -d $LOGS_DIR ]; then
    mkdir $LOGS_DIR
fi
#日志
STDOUT_FILE=$LOGS_DIR/stdout.log
#JAVA 环境配置
JAVA_OPTS=" -Djava.net.preferIPv4Stack=true -Dlog.home=$LOGS_DIR"

JAVA_MEM_OPTS=" -server -Xms1024m -Xmx1024m -XX:MetaspaceSize=64m -XX:MaxMetaspaceSize=256m  -XX:+UseG1GC -XX:MaxGCPauseMillis=100 -XX:InitiatingHeapOccupancyPercent=50 -XX:+PrintGCApplicationStoppedTime -XX:+PrintGCApplicationConcurrentTime -XX:+PrintGCDateStamps -verbose:gc -XX:+PrintGCDetails -XX:+PrintHeapAtGC -Xloggc:$LOGS_DIR/gc.log -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=100M -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=dump.hprof "
#退出标志
RETVAL="0"

if [ -n "$PIDS" ]; then
		echo "ERROR: The $SERVER_NAME already started!"
		echo "PID: $PIDS"
		exit $RETVAL
fi

nohup java -jar  $JAVA_OPTS $JAVA_MEM_OPTS  -Dloader.path=conf,lib $ENGINE > $STDOUT_FILE 2>&1 &
COUNT=0
	while [ $COUNT -lt 1 ]; do
		echo -e ".\c"
		sleep 1
		COUNT=`ps -f | grep java | grep "$DEPLOY_DIR" | awk '{print $2}' | wc -l`
		if [ $COUNT -gt 0 ]; then
			break
		fi
	done

	echo "OK!"
	PIDS=`ps -f | grep java | grep "$DEPLOY_DIR" | awk '{print $2}'`
	echo "PID: $PIDS"
	echo "STDOUT: $STDOUT_FILE"

ENGINE 改为项目名称

1.3 在项目名称/src/main/build/scripts创建 stop.sh

#!/bin/bash
SERVER_NAME=novel-front.jar

#应用进程
PIDS=`ps -ef | grep java | grep "$SERVER_NAME" |awk '{print $2}'`
if [ -z "$PIDS" ]; then
    		echo "ERROR: The $SERVER_NAME does not started!"
    	exit 1
	fi

	echo -e "Stopping the $SERVER_NAME ...\c"
	for PID in $PIDS ; do
    		kill $PID > /dev/null 2>&1
	done

	COUNT=0
	while [ $COUNT -lt 1 ]; do
    		echo -e ".\c"
    		sleep 1
    		COUNT=1
    		for PID in $PIDS ; do
        	PID_EXIST=`ps -f -p $PID | grep java`
        	if [ -n "$PID_EXIST" ]; then
            		COUNT=0
            		break
        	fi
    		done
	done

	echo "OK!"
	echo "PID: $PIDS"
	PIDS=""


ENGINE 改为项目名称

1.4 在项目名称/src/main/build/scripts下创建 windows-start.bat

@echo off
setlocal enabledelayedexpansion
set JAVA=java

set OPTS=-XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=128m -Xms1024m -Xmx1024m -Xmn256m -Xss256k -XX:SurvivorRatio=8 -XX:+UseConcMarkSweepGC
set ENGINE=novel-front.jar
cd ../
java -jar %OPTS%   -Dloader.path=conf,lib %ENGINE%
pause


ENGINE 改为项目名称

问题:

windows编写sh脚本在linux上不能执行

报错:/bin/sh^M:bad interpreter:

编码没有被识别,

*vi .sh

Esc 输入 :set fileformat

  • 查看文件格式(显示 fileformat=dos)

Esc输入 :set fileformat=unix

  • 保存

Esc 输入 :set fileformat

  • 修改文件格式(修改后 显示 fileformat=unix)

Esc输入 :wq

最后重新执行sh文件

2.根据服务器的配置 运行下面命令 (为了方便观看 换行了 执行的时候把换行去掉)

nohup java -jar   -Djava.net.preferIPv4Stack=true -Dlog.home=/tmp/logs 
-server 
-Xms1024m 
-Xmx1024m 
-XX:MetaspaceSize=64m 
-XX:MaxMetaspaceSize=256m  
-XX:+UseG1GC 
-XX:MaxGCPauseMillis=100 
-XX:InitiatingHeapOccupancyPercent=50 
-XX:+PrintGCApplicationStoppedTime 
-XX:+PrintGCApplicationConcurrentTime 
-XX:+PrintGCDateStamps 
-verbose:gc 
-XX:+PrintGCDetails 
-XX:+PrintHeapAtGC 
-Xloggc:/tmp/logs/gc.log 
-XX:+UseGCLogFileRotation 
-XX:NumberOfGCLogFiles=10 
-XX:GCLogFileSize=100M 
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=dump.hprof 
-Dloader.path=conf,lib 打包的jar.jar > /tmp/logs/stdout.log  2>&1 &

或简单点

java -jar -Dloader.path=conf,lib 打包的jar.jar > /tmp/logs/stdout.log  2>&1 &

/tmp/logs 替换为日志目录

打包的jar.jar 替换为 打包后build下的jar名称

image.png

docker-compose.yml

  xsadmin:
    container_name: xs-admin
    image: openjdk:8
    restart: always
    volumes:
      - /opt/docker/java/novel/upload/:/var/pic/
      - /opt/docker/java/novel-admin:/opt/app/
      - /opt/docker/java/novel-admin/logs:/opt/app/logs/
      - /etc/localtime:/etc/localtime:ro
    expose:
      - "8088"
    ports:
      - "8088:8088"
    depends_on:
      - mymysql
      - myredis
    command:
      - /bin/bash
      - -c
      - |
        cd /opt/app
        java  -Djava.net.preferIPv4Stack=true -Dlog.home=logs -server  -Xmx1g -Xms1g -Xmn384m -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=70 -XX:+UseCMSInitiatingOccupancyOnly -XX:+UnlockDiagnosticVMOptions -XX:ParGCCardsPerStrideChunk=4096 -XX:MetaspaceSize=200m -XX:+PrintGCApplicationStoppedTime -XX:+PrintGCApplicationConcurrentTime -XX:+PrintGCDateStamps -verbose:gc -XX:+PrintGCDetails -XX:+PrintHeapAtGC -Xloggc:logs/gc.log -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=100M -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=logs/dump.hprof    -Dloader.path=conf,lib -jar novel-admin.jar

标题:spring boot 分离打包
作者:不断努力的青春
地址:http://songaw.com/articles/2022/01/26/1643166338051.html