Spring Boot項目使用maven-assembly-plugin根據(jù)不同環(huán)境打包成tar.gz或者zip

spring-boot-assembly

  1. 在spring boot項目中使用maven profiles和maven assembly插件根據(jù)不同環(huán)境打包成tar.gz或者zip
  2. 將spring boot項目中的配置文件提取到外部config目錄中
  3. 將spring boot項目中的啟動jar包移動到boot目錄中
  4. 將spring boot項目中的第三方依賴jar包移動到外部lib目錄中
  5. bin目錄中是啟動晨逝,停止蛾默,重啟服務(wù)命令
  6. 打包后的目錄結(jié)構(gòu)類似于tomcat/maven目錄結(jié)構(gòu)

代碼托管

Gitee

主要插件

  1. maven-assembly-plugin
  2. maven-jar-plugin
  3. spring-boot-maven-plugin
  4. maven-dependency-plugin
  5. maven-resources-plugin

1.maven-assembly-plugin 配置assembly.xml文件路徑

<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>

2.assembly.xml打包配置文件

<?xml version="1.0" encoding="UTF-8"?>
<assembly>
    <!-- 可自定義,這里指定的是項目環(huán)境 -->
    <!-- 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->即用戶具有讀/寫/執(zhí)行權(quán)限,組用戶和其它用戶具有讀寫權(quán)限昏翰;
            0644->即用戶具有讀寫權(quán)限,組用戶和其它用戶具有只讀權(quán)限刘急;
        -->
        <!-- 將src/bin目錄下的所有文件輸出到打包后的bin目錄中 -->
        <fileSet>
            <directory>${basedir}/src/bin</directory>
            <outputDirectory>bin</outputDirectory>
            <fileMode>0755</fileMode>
            <includes>
                <include>**.sh</include>
                <include>**.bat</include>
            </includes>
        </fileSet>

        <!-- 指定輸出target/classes中的配置文件到config目錄中 -->
        <fileSet>
            <directory>${basedir}/target/classes</directory>
            <outputDirectory>config</outputDirectory>
            <fileMode>0644</fileMode>
            <includes>
                <include>application.yml</include>
                <include>application-${profileActive}.yml</include>
                <include>mapper/**/*.xml</include>
                <include>static/**</include>
                <include>templates/**</include>
                <include>*.xml</include>
                <include>*.properties</include>
            </includes>
        </fileSet>

        <!-- 將第三方依賴打包到lib目錄中 -->
        <fileSet>
            <directory>${basedir}/target/lib</directory>
            <outputDirectory>lib</outputDirectory>
            <fileMode>0755</fileMode>
        </fileSet>

        <!-- 將項目啟動jar打包到boot目錄中 -->
        <fileSet>
            <directory>${basedir}/target</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>

3.spring-boot-maven-plugin 排除啟動jar包中依賴的jar包

<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>

4.maven-jar-plugin 自定義maven jar打包內(nèi)容

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>3.1.0</version>
    <configuration>
        <archive>
            <manifest>
                <!-- 項目啟動類 -->
                <mainClass>Application</mainClass>
                <!-- 依賴的jar的目錄前綴 -->
                <classpathPrefix>../lib</classpathPrefix>
                <addClasspath>true</addClasspath>
            </manifest>
        </archive>
        <includes>
            <!-- 只打包指定目錄的文件 -->
            <include>io/geekidea/springboot/**</include>
        </includes>
    </configuration>
</plugin>    

5.maven-dependency-plugin 復(fù)制項目的依賴包到指定目錄

<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>

6.maven-resources-plugin

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

<resource>
    <directory>src/main/resources</directory>
    <filtering>true</filtering>
    <includes>
        <include>application.yml</include>
        <include>application-${profileActive}.yml</include>
        <include>mapper/**/*.xml</include>
        <include>static/**</include>
        <include>templates/**</include>
        <include>*.xml</include>
        <include>*.properties</include>
    </includes>
</resource>

7.maven profiles配置

<!--MAVEN打包選擇運行環(huán)境-->
<!-- 1:local(默認(rèn)) 本地 2:dev:開發(fā)環(huán)境 3:test 4:uat 用戶驗收測試 5.pro:生產(chǎn)環(huán)境-->
<profiles>
    <profile>
        <id>local</id>
        <properties>
            <profileActive>local</profileActive>
        </properties>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
    </profile>
    <profile>
        <id>dev</id>
        <properties>
            <profileActive>dev</profileActive>
        </properties>
        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>
    </profile>
    <profile>
        <id>test</id>
        <properties>
            <profileActive>test</profileActive>
        </properties>
        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>
    </profile>
    <profile>
        <id>uat</id>
        <properties>
            <profileActive>uat</profileActive>
        </properties>
        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <profileActive>prod</profileActive>
        </properties>
        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>
    </profile>
</profiles>

8.阿里云倉庫配置

<repositories>
    <!--阿里云倉庫-->
    <repository>
        <id>aliyun</id>
        <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
    </repository>
</repositories>


項目源碼結(jié)構(gòu)
├─bin
│      restart.sh
│      shutdown.sh
│      startup.bat
│      startup.sh
│
├─logs
│      springboot-assembly.log
│
├─main
│  ├─assembly
│  │      assembly.xml
│  │
│  ├─java
│  │  └─io
│  │      └─geekidea
│  │          └─springboot
│  │              └─assembly
│  │                      Application.java
│  │                      HelloController.java
│  │                      HelloService.java
│  │                      HelloServiceImpl.java
│  │
│  └─resources
│      │  application-dev.yml
│      │  application-local.yml
│      │  application-prod.yml
│      │  application-test.yml
│      │  application-uat.yml
│      │  application.yml
│      │
│      ├─mapper
│      │  │  test.xml
│      │  │
│      │  └─hello
│      │          hello.xml
│      │
│      ├─static
│      │      index.html
│      │
│      └─templates
│              test.txt
│
└─test

項目打包
mvn clean package

使用maven assembly插件打包local環(huán)境后的壓縮包,target目錄下
spring-boot-assembly-local-1.0.RELEASE.tar.gz

linux解壓tar.gz
tar -zxvf spring-boot-assembly-local-1.0.RELEASE.tar.gz

解壓后的目錄結(jié)構(gòu)
└─spring-boot-assembly
    │  LICENSE
    │  NOTICE
    │  README.md
    │
    ├─bin
    │      restart.sh
    │      shutdown.sh
    │      startup.bat
    │      startup.sh
    │
    ├─boot
    │      spring-boot-assembly.jar
    │
    ├─config
    │  │  application-local.yml
    │  │  application.yml
    │  │
    │  ├─mapper
    │  │  │  test.xml
    │  │  │
    │  │  └─hello
    │  │          hello.xml
    │  │
    │  ├─static
    │  │      index.html
    │  │
    │  └─templates
    │          test.txt
    │
    └─lib
            classmate-1.4.0.jar
            fastjson-1.2.54.jar
            hibernate-validator-6.0.13.Final.jar
            jackson-annotations-2.9.0.jar
            jackson-core-2.9.7.jar
            jackson-databind-2.9.7.jar
            jackson-datatype-jdk8-2.9.7.jar
            jackson-datatype-jsr310-2.9.7.jar
            jackson-module-parameter-names-2.9.7.jar
            javax.annotation-api-1.3.2.jar
            jboss-logging-3.3.2.Final.jar
            jul-to-slf4j-1.7.25.jar
            log4j-api-2.11.1.jar
            log4j-to-slf4j-2.11.1.jar
            logback-classic-1.2.3.jar
            logback-core-1.2.3.jar
            slf4j-api-1.7.25.jar
            snakeyaml-1.23.jar
            spring-aop-5.1.2.RELEASE.jar
            spring-beans-5.1.2.RELEASE.jar
            spring-boot-2.1.0.RELEASE.jar
            spring-boot-autoconfigure-2.1.0.RELEASE.jar
            spring-boot-starter-2.1.0.RELEASE.jar
            spring-boot-starter-json-2.1.0.RELEASE.jar
            spring-boot-starter-logging-2.1.0.RELEASE.jar
            spring-boot-starter-tomcat-2.1.0.RELEASE.jar
            spring-boot-starter-web-2.1.0.RELEASE.jar
            spring-context-5.1.2.RELEASE.jar
            spring-core-5.1.2.RELEASE.jar
            spring-expression-5.1.2.RELEASE.jar
            spring-jcl-5.1.2.RELEASE.jar
            spring-web-5.1.2.RELEASE.jar
            spring-webmvc-5.1.2.RELEASE.jar
            tomcat-embed-core-9.0.12.jar
            tomcat-embed-el-9.0.12.jar
            tomcat-embed-websocket-9.0.12.jar
            validation-api-2.0.1.Final.jar


window啟動,會打開瀏覽器棚菊,訪問項目測試路徑
bin/startup.bat

{"msg":"service hello:123","code":200}

linux啟動,停止叔汁,重啟
sh bin/startup.sh   啟動項目
sh bin/shutdown.sh  停止服務(wù)
sh bin/restart.sh   重啟服務(wù)

startup.sh 腳本中的主要內(nèi)容
  • 配置項目名稱及項目啟動jar名稱统求,默認(rèn)項目名稱與啟動jar名稱一致
APPLICATION="spring-boot-assembly"
APPLICATION_JAR="${APPLICATION}.jar"

  • JAVA_OPTION配置
  • JVM Configuration
  • -Xmx256m:設(shè)置JVM最大可用內(nèi)存為256m,根據(jù)項目實際情況而定,建議最小和最大設(shè)置成一樣据块。
  • -Xms256m:設(shè)置JVM初始內(nèi)存码邻。此值可以設(shè)置與-Xmx相同,以避免每次垃圾回收完成后JVM重新分配內(nèi)存
  • -Xmn512m:設(shè)置年輕代大小為512m。整個JVM內(nèi)存大小=年輕代大小 + 年老代大小 + 持久代大小另假。持久代一般固定大小為64m,所以增大年輕代,將會減小年老代大小像屋。此值對系統(tǒng)性能影響較大,Sun官方推薦配置為整個堆的3/8
  • -XX:MetaspaceSize=64m:存儲class的內(nèi)存大小,該值越大觸發(fā)Metaspace GC的時機(jī)就越晚
  • -XX:MaxMetaspaceSize=320m:限制Metaspace增長的上限,防止因為某些情況導(dǎo)致Metaspace無限的使用本地內(nèi)存边篮,影響到其他程序
  • -XX:-OmitStackTraceInFastThrow:解決重復(fù)異常不打印堆棧信息問題
JAVA_OPT="-server -Xms256m -Xmx256m -Xmn512m -XX:MetaspaceSize=64m -XX:MaxMetaspaceSize=256m"
JAVA_OPT="${JAVA_OPT} -XX:-OmitStackTraceInFastThrow"

執(zhí)行啟動命令:后臺啟動項目,并將日志輸出到項目根目錄下的logs文件夾下

nohup java ${JAVA_OPT} -jar ${BASE_PATH}/boot/${APPLICATION_JAR} --spring.config.location=${CONFIG_DIR} > ${LOG_PATH} 2>&1 &

最終執(zhí)行jar包的命令

nohup java -server -Xms256m -Xmx256m -Xmn512m -XX:MetaspaceSize=64m -XX:MaxMetaspaceSize=256m -XX:-OmitStackTraceInFastThrow -jar /opt/spring-boot-assembly/boot/spring-boot-assembly.jar --spring.config.location=/opt/spring-boot-assembly/config/ > /opt/spring-boot-assembly/logs/spring-boot-assembly.log 2>&1 &

  • nohup:在后臺運行jar包己莺,然后將運行日志輸出到指定位置
  • -server:指定JVM參數(shù)
  • -jar /opt/spring-boot-assembly/boot/spring-boot-assembly.jar:指定啟動的jar包
  • 啟動命令中指定的啟動jar包路徑,配置文件路徑戈轿,日志路徑都是絕對路徑
  • 可在任何位置執(zhí)行start.sh, shutdown.sh,restart.sh腳本
  • –spring.config.location:指定配置文件目錄或者文件名稱凌受,如果是目錄,以/結(jié)束
  • /opt/spring-boot-assembly/logs/spring-boot-assembly.log:指定日志輸出路徑

  • 2>&1 & :將正常的運行日志和錯誤日志合并輸入到指定日志思杯,并在后臺運行

shutdown.sh停服腳本胜蛉,實現(xiàn)方式:找到當(dāng)前項目的PID,然后kill -9

PID=$(ps -ef | grep "${APPLICATION_JAR}" | grep -v grep | awk '{ print $2 }')
kill -9 ${PID}

日志記錄

項目啟動日志存儲路徑,一個項目只有一個啟動日志文件
logs/spring-boot-assembly_startup.log

================================================ 2018-12-12 12:36:56 ================================================
application name: spring-boot-assembly
application jar name: spring-boot-assembly.jar
application bin path: /opt/spring-boot-assembly/bin
application root path: /opt/spring-boot-assembly
application log path: /opt/spring-boot-assembly/logs/spring-boot-assembly.log
application JAVA_OPT : -server -Xms256m -Xmx256m -Xmn512m -XX:MetaspaceSize=64m -XX:MaxMetaspaceSize=256m -XX:-OmitStackTraceInFastThrow
application background startup command: nohup java -server -Xms256m -Xmx256m -Xmn512m -XX:MetaspaceSize=64m -XX:MaxMetaspaceSize=256m -XX:-OmitStackTraceInFastThrow -jar /opt/spring-boot-assembly/boot/spring-boot-assembly.jar --spring.config.location=/opt/spring-boot-assembly/config/ > /opt/spring-boot-assembly/logs/spring-boot-assembly.log 2>&1 &
application pid: 11596

項目運行日志存儲路徑誊册,最近一次啟動項目的運行日志
logs/spring-boot-assembly.log

.   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.0.RELEASE)

2018-12-12 23:28:58.420  INFO 11596 --- [           main] o.s.boot.SpringApplication               : Starting application on VM_0_17_centos with PID 11596 (started by root in /opt/spring-boot-assembly)
2018-12-12 23:28:58.442  INFO 11596 --- [           main] o.s.boot.SpringApplication               : The following profiles are active: local
2018-12-12 23:29:01.355  INFO 11596 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2018-12-12 23:29:01.437  INFO 11596 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-12-12 23:29:01.437  INFO 11596 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/9.0.12
2018-12-12 23:29:01.461  INFO 11596 --- [           main] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib]
2018-12-12 23:29:01.646  INFO 11596 --- [           main] o.a.c.c.C.[.[localhost].[/example]       : Initializing Spring embedded WebApplicationContext
2018-12-12 23:29:01.647  INFO 11596 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3028 ms
2018-12-12 23:29:01.708  INFO 11596 --- [           main] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-12-12 23:29:01.712  INFO 11596 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-12-12 23:29:01.712  INFO 11596 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-12-12 23:29:01.712  INFO 11596 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'formContentFilter' to: [/*]
2018-12-12 23:29:01.713  INFO 11596 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-12-12 23:29:02.250  INFO 11596 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2018-12-12 23:29:03.179  INFO 11596 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path '/example'
2018-12-12 23:29:03.182  INFO 11596 --- [           main] o.s.boot.SpringApplication               : Started application in 5.844 seconds (JVM running for 6.547)
spring.profiles.active = local
contextPath = /example
server.port = 8080
hello = Hello Local
http://localhost:8080/example/hello?name=123

項目歷史運行日志存儲路徑领突,每啟動一次項目,會將之前的運行日志移動到back目錄
`-- logs
    |-- back
    |   |-- spring-boot-assembly_back_2018-12-12-23-30-10.log
    |   `-- spring-boot-assembly_back_2018-12-12-23-36-56.log
    |-- spring-boot-assembly.log
    `-- spring-boot-assembly_startup.log

maven項目打包

1. 使用IDEA工具打包,選擇對應(yīng)的profiles,然后clean package
mvn-clean-package-local
mvn-clean-package-dev
2. 使用maven命令打包
mvn clean package -Pdev

3. 使用mvn-package腳本打包

window

mvn-package.bat dev

linux/mac

sh mvn-package.sh dev

FAQ

Q: 項目打成tar包后解虱,不能正常讀取resource目錄下的某些配置文件
A:如果resource目錄中還用到其它配置文件攘须,需要在pom.xml和assembly.xml文件的resource中進(jìn)行配置
  1. pom.xml中的resource默認(rèn)配置

把需要打包的文件添加到include中

<!-- 資源文件配置 -->
<resource>
    <directory>src/main/resources</directory>
    <filtering>true</filtering>
    <includes>
        <include>application.yml</include>
        <include>application-${profileActive}.yml</include>
        <include>mapper/**/*.xml</include>
        <include>static/**</include>
        <include>templates/**</include>
        <include>*.xml</include>
        <include>*.properties</include>
        <!-- xxx.keystore -->
        <include>xxx.keystore</include>
    </includes>
</resource>

  1. assembly.xml中的resource默認(rèn)配置

把需要打包的文件添加到include中

<!-- 指定輸出target/classes中的配置文件到config目錄中 -->
<fileSet>
    <directory>${basedir}/target/classes</directory>
    <outputDirectory>config</outputDirectory>
    <fileMode>0644</fileMode>
    <includes>
        <include>application.yml</include>
        <include>application-${profileActive}.yml</include>
        <include>mapper/**/*.xml</include>
        <include>static/**</include>
        <include>templates/**</include>
        <include>*.xml</include>
        <include>*.properties</include>
        <!-- xxx.keystore -->
        <include>xxx.keystore</include>
    </includes>
</fileSet>

參考:
startup.sh
#! /bin/shell

#======================================================================
# 項目啟動shell腳本
# boot目錄: spring boot jar包
# config目錄: 配置文件目錄
# logs目錄: 項目運行日志目錄
# logs/spring-boot-assembly_startup.log: 記錄啟動日志
# logs/back目錄: 項目運行日志備份目錄
# nohup后臺運行
#
#======================================================================

# 項目名稱
APPLICATION="spring-boot-assembly"

# 項目啟動jar包名稱
APPLICATION_JAR="${APPLICATION}.jar"

# bin目錄絕對路徑
BIN_PATH=$(cd `dirname $0`; pwd)
# 進(jìn)入bin目錄
cd `dirname $0`
# 返回到上一級項目根目錄路徑
cd ..
# 打印項目根目錄絕對路徑
# `pwd` 執(zhí)行系統(tǒng)命令并獲得結(jié)果
BASE_PATH=`pwd`

# 外部配置文件絕對目錄,如果是目錄需要/結(jié)尾,也可以直接指定文件
# 如果指定的是目錄,spring則會讀取目錄中的所有配置文件
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}/${APPLICATION}_startup.log"

# 當(dāng)前時間
NOW=`date +'%Y-%m-%m-%H-%M-%S'`
NOW_PRETTY=`'date +%Y-%m-%m %H:%M:%S'`

# 啟動日志
STARTUP_LOG="================================================ ${NOW_PRETTY} ================================================\n"

# 如果logs文件夾不存在,則創(chuàng)建文件夾
if [[ ! -d "${LOG_DIR}" ]]; then
  mkdir "${LOG_DIR}"
fi

# 如果logs/back文件夾不存在,則創(chuàng)建文件夾
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

# 創(chuàng)建新的項目運行日志
echo "" > ${LOG_PATH}

# 如果項目啟動日志不存在,則創(chuàng)建,否則追加
echo "${STARTUP_LOG}" >> ${LOG_STARTUP_PATH}

#==========================================================================================
# JVM Configuration
# -Xmx256m:設(shè)置JVM最大可用內(nèi)存為256m,根據(jù)項目實際情況而定殴泰,建議最小和最大設(shè)置成一樣于宙。
# -Xms256m:設(shè)置JVM初始內(nèi)存。此值可以設(shè)置與-Xmx相同,以避免每次垃圾回收完成后JVM重新分配內(nèi)存
# -Xmn512m:設(shè)置年輕代大小為512m悍汛。整個JVM內(nèi)存大小=年輕代大小 + 年老代大小 + 持久代大小捞魁。
#          持久代一般固定大小為64m,所以增大年輕代,將會減小年老代大小。此值對系統(tǒng)性能影響較大,Sun官方推薦配置為整個堆的3/8
# -XX:MetaspaceSize=64m:存儲class的內(nèi)存大小,該值越大觸發(fā)Metaspace GC的時機(jī)就越晚
# -XX:MaxMetaspaceSize=320m:限制Metaspace增長的上限离咐,防止因為某些情況導(dǎo)致Metaspace無限的使用本地內(nèi)存暴凑,影響到其他程序
# -XX:-OmitStackTraceInFastThrow:解決重復(fù)異常不打印堆棧信息問題
#==========================================================================================
JAVA_OPT="-server -Xms256m -Xmx256m -Xmn512m -XX:MetaspaceSize=64m -XX:MaxMetaspaceSize=256m"
JAVA_OPT="${JAVA_OPT} -XX:-OmitStackTraceInFastThrow"

#=======================================================
# 將命令啟動相關(guān)日志追加到日志文件
#=======================================================

# 輸出項目名稱
STARTUP_LOG="${STARTUP_LOG}application name: ${APPLICATION}\n"
# 輸出jar包名稱
STARTUP_LOG="${STARTUP_LOG}application jar name: ${APPLICATION_JAR}\n"
# 輸出項目bin路徑
STARTUP_LOG="${STARTUP_LOG}application bin  path: ${BIN_PATH}\n"
# 輸出項目根目錄
STARTUP_LOG="${STARTUP_LOG}application root path: ${BASE_PATH}\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 background startup command: nohup java ${JAVA_OPT} -jar ${BASE_PATH}/boot/${APPLICATION_JAR} --spring.config.location=${CONFIG_DIR} > ${LOG_PATH} 2>&1 &\n"

#======================================================================
# 執(zhí)行啟動命令:后臺啟動項目,并將日志輸出到項目根目錄下的logs文件夾下
#======================================================================
nohup java ${JAVA_OPT} -jar ${BASE_PATH}/boot/${APPLICATION_JAR} --spring.config.location=${CONFIG_DIR} > ${LOG_PATH} 2>&1 &

# 進(jìn)程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}

startup.bat
@echo off
rem ======================================================================
rem windows startup script
rem
rem ======================================================================

rem Open in a browser
start "" "http://localhost:8080/example/hello?name=123"

rem startup jar
java -jar ../boot/spring-boot-assembly.jar --spring.config.location=../config/

pause

shutdown.sh
#! /bin/shell

#======================================================================
# 項目停服shell腳本
# 通過項目名稱查找到PID
# 然后kill -9 pid
#
#======================================================================

# 項目名稱
APPLICATION="spring-boot-assembly"

# 項目啟動jar包名稱
APPLICATION_JAR="${APPLICATION}.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 -9 ${PID}
    echo ${APPLICATION} stopped successfully
fi

restart.sh
#! /bin/shell

#======================================================================
# 項目重啟shell腳本
# 先調(diào)用shutdown.sh停服
# 然后調(diào)用startup.sh啟動服務(wù)
#
#======================================================================

# 項目名稱
APPLICATION="spring-boot-assembly"

# 停服
echo stop ${APPLICATION} Application...
sh shutdown.sh

# 啟動服務(wù)
echo start ${APPLICATION} Application...
sh startup.sh

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末藏澳,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌诫欠,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,372評論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件燎字,死亡現(xiàn)場離奇詭異螺句,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)梧宫,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評論 3 392
  • 文/潘曉璐 我一進(jìn)店門接谨,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人塘匣,你說我怎么就攤上這事脓豪。” “怎么了忌卤?”我有些...
    開封第一講書人閱讀 162,415評論 0 353
  • 文/不壞的土叔 我叫張陵扫夜,是天一觀的道長。 經(jīng)常有香客問我埠巨,道長历谍,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,157評論 1 292
  • 正文 為了忘掉前任辣垒,我火速辦了婚禮望侈,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘勋桶。我一直安慰自己脱衙,他們只是感情好侥猬,可當(dāng)我...
    茶點故事閱讀 67,171評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著捐韩,像睡著了一般退唠。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上荤胁,一...
    開封第一講書人閱讀 51,125評論 1 297
  • 那天瞧预,我揣著相機(jī)與錄音,去河邊找鬼仅政。 笑死垢油,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的圆丹。 我是一名探鬼主播滩愁,決...
    沈念sama閱讀 40,028評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼辫封!你這毒婦竟也來了硝枉?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,887評論 0 274
  • 序言:老撾萬榮一對情侶失蹤倦微,失蹤者是張志新(化名)和其女友劉穎妻味,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體欣福,經(jīng)...
    沈念sama閱讀 45,310評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡弧可,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,533評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了劣欢。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,690評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡裁良,死狀恐怖凿将,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情价脾,我是刑警寧澤牧抵,帶...
    沈念sama閱讀 35,411評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站侨把,受9級特大地震影響犀变,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜秋柄,卻給世界環(huán)境...
    茶點故事閱讀 41,004評論 3 325
  • 文/蒙蒙 一获枝、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧骇笔,春花似錦省店、人聲如沸嚣崭。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽雹舀。三九已至,卻和暖如春粗俱,著一層夾襖步出監(jiān)牢的瞬間说榆,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評論 1 268
  • 我被黑心中介騙來泰國打工寸认, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留签财,地道東北人。 一個月前我還...
    沈念sama閱讀 47,693評論 2 368
  • 正文 我出身青樓废麻,卻偏偏與公主長得像荠卷,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子烛愧,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,577評論 2 353

推薦閱讀更多精彩內(nèi)容