Spring Boot 部署與服務配置

來源:互聯網
上載者:User

Spring Boot 部署與服務配置

Spring Boot 其預設是整合web容器的,啟動方式由像普通Java程式一樣,main函數入口啟動。其內建Tomcat容器或Jetty容器,具體由配置來決定(預設Tomcat)。當然你也可以將項目打包成war包,放到獨立的web容器中(Tomcat、weblogic等等),當然在此之前你要對程式入口做簡單調整。

項目構建我們使用Maven或Gradle,這將使項目依賴、jar包管理、以及打包部署變的非常方便。

一、內嵌 Server 配置

Spring Boot將容器內建後,它通過設定檔的方式類修改相關server配置。
先看一下下面的圖,為關於server的配置列項:

其中常用的配置只有少數幾個,已經用紫色標記起來。紅框圈起來的部分,看名稱分類就可以明白其作用。
對server的幾個常用的配置做個簡單說明:

# 項目contextPath,一般在正式發布版本中,我們不配置server.context-path=/myspringboot# 錯誤頁,指定發生錯誤時,跳轉的URL。請查看BasicErrorController源碼便知server.error.path=/error# 服務連接埠server.port=9090# session最大逾時時間(分鐘),預設為30server.session-timeout=60# 該服務綁定IP地址,啟動伺服器時如本機不是該IP地址則拋出異常啟動失敗,只有特殊需求的情況下才配置# server.address=192.168.16.11

Tomcat
Tomcat為Spring Boot的預設容器,下面是幾個常用配置:

# tomcat最大線程數,預設為200server.tomcat.max-threads=800# tomcat的URI編碼server.tomcat.uri-encoding=UTF-8# 存放Tomcat的日誌、Dump等檔案的臨時檔案夾,預設為系統的tmp檔案夾(如:C:\Users\Shanhy\AppData\Local\Temp)server.tomcat.basedir=H:/springboot-tomcat-tmp# 開啟Tomcat的Access日誌,並可以設定日誌格式的方法:#server.tomcat.access-log-enabled=true#server.tomcat.access-log-pattern=# accesslog目錄,預設在basedir/logs#server.tomcat.accesslog.directory=# 記錄檔目錄logging.path=H:/springboot-tomcat-tmp# 記錄檔名稱,預設為spring.loglogging.file=myapp.log

Jetty
如果你要選擇Jetty,也非常簡單,就是把pom中的tomcat依賴排除,並加入Jetty容器的依賴,如下:

<code class=" hljs xml"><dependencies>  <dependency>    <groupid>org.springframework.boot</groupid>    <artifactid>spring-boot-starter-web</artifactid>    <exclusions>      <exclusion>        <groupid>org.springframework.boot</groupid>        <artifactid>spring-boot-starter-tomcat</artifactid>      </exclusion>    </exclusions>  </dependency>  <dependency>    <groupid>org.springframework.boot</groupid>    <artifactid>spring-boot-starter-jetty</artifactid>  </dependency><dependencies> </dependencies></dependencies></code>

打包
打包方法:
CMD進入項目目錄,使用 mvn clean package 命令打包,以我的項目工程為例:

E:\spring-boot-sample>mvn clean package

可以追加參數 -Dmaven.test.skip=true 跳過測試。
打包後的檔案存放於項目下的target目錄中,如:spring-boot-sample-0.0.1-SNAPSHOT.jar
如果pom配置的是war包,則為spring-boot-sample-0.0.1-SNAPSHOT.war

二、部署到JavaEE容器修改啟動類,繼承 SpringBootServletInitializer 並重寫 configure 方法
public class SpringBootSampleApplication extends SpringBootServletInitializer{    private static final Logger logger = LoggerFactory.getLogger(SpringBootSampleApplication.class);    @Override    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {        return builder.sources(this.getClass());    }}
修改pom檔案中jar 為 war
<code class=" hljs xml"><!--{cke_protected}{C}%3C!%2D%2D%20%3Cpackaging%3Ejar%3C%2Fpackaging%3E%20%2D%2D%3E--><packaging>war</packaging></code>
修改pom,排除tomcat外掛程式
<code class=" hljs xml">        <dependency>            <groupid>org.springframework.boot</groupid>            <artifactid>spring-boot-starter-web</artifactid>            <exclusions>                <exclusion>                    <groupid>org.springframework.boot</groupid>                    <artifactid>spring-boot-starter-tomcat</artifactid>                </exclusion>            </exclusions>        </dependency></code>
打包部署到容器
使用命令 mvn clean package 打包後,同一般J2EE項目一樣部署到web容器。三、使用Profile區分環境

spring boot 可以在 “設定檔”、“Java代碼類”、“日誌配置” 中來配置profile區分不同環境執行不同的結果

1、設定檔
使用設定檔application.yml 和 application.properties 有所區別
以application.properties 為例,通過檔案名稱來區分環境 application-{profile}.properties
application.properties

app.name=MyAppserver.port=8080spring.profiles.active=dev

application-dev.properties

server.port=8081

application-stg.properties

server.port=8082

在啟動程式的時候通過添加 –spring.profiles.active={profile} 來指定具體使用的配置
例如我們執行 java -jar demo.jar –spring.profiles.active=dev 那麼上面3個檔案中的內容將被如何應用?
Spring Boot 會先載入預設的設定檔,然後使用具體指定的profile中的配置去覆蓋預設配置。

app.name 只存在於預設設定檔 application.properties 中,因為指定環境中不存在同樣的配置,所以該值不會被覆蓋
server.port 預設為8080,但是我們指定了環境後,將會被覆蓋。如果指定stg環境,server.port 則為 8082
spring.profiles.active 預設指定dev環境,如果我們在運行時指定 –spring.profiles.active=stg 那麼將應用stg環境,最終 server.port 的值為8082

2、Java類中@Profile註解
下面2個不同的類實現了同一個介面,@Profile註解指定了具體環境

// 介面定義public interface SendMessage {    // 傳送簡訊方法定義    public void send();}// Dev 環境實作類別@Component@Profile("dev")public class DevSendMessage implements SendMessage {    @Override    public void send() {        System.out.println(">>>>>>>>Dev Send()<<<<<<<<");    }}// Stg環境實作類別@Component@Profile("stg")public class StgSendMessage implements SendMessage {    @Override    public void send() {        System.out.println(">>>>>>>>Stg Send()<<<<<<<<");    }}// 啟動類@SpringBootApplicationpublic class ProfiledemoApplication {    @Value("${app.name}")    private String name;    @Autowired    private SendMessage sendMessage;    @PostConstruct    public void init(){        sendMessage.send();// 會根據profile指定的環境執行個體化對應的類    }}

3、logback-spring.xml也支援有節點來支援區分

<code class=" hljs xml"><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%2D%2D%3E--><configuration>    <include resource="org/springframework/boot/logging/logback/base.xml">    <logger name="org.springframework.web" level="INFO">    <springprofile name="default">        <logger name="org.springboot.sample" level="TRACE">    </logger></springprofile>    <springprofile name="dev">        <logger name="org.springboot.sample" level="DEBUG">    </logger></springprofile>    <springprofile name="staging">        <logger name="org.springboot.sample" level="INFO">    </logger></springprofile></logger></include></configuration></code>

再說一遍檔案名稱不要用logback.xml 請使用logback-spring.xml

四、指定外部的設定檔

有些系統,關於一些資料庫或其他第三方賬戶等資訊,由於安全問題,其配置並不會提前配置在項目中暴露給開發人員。
對於這種情況,我們在運行程式的時候,可以通過參數指定一個外部設定檔。
以 demo.jar 為例,方法如下:

java -jar demo.jar --spring.config.location=/opt/config/application.properties

其中檔案名稱隨便定義,無固定要求。

五、建立一個Linux 應用的sh指令碼

下面幾個指令碼僅供參考,請根據自己需要做調整
start.sh

#!/bin/shrm -f tpidnohup java -jar /data/app/myapp.jar --spring.profiles.active=stg > /dev/null 2>&1 &echo $! > tpid

stop.sh

tpid=`cat tpid | awk '{print $1}'`tpid=`ps -aef | grep $tpid | awk '{print $2}' |grep $tpid`if [ ${tpid} ]; then        kill -9 $tpidfi

check.sh

#!/bin/shtpid=`cat tpid | awk '{print $1}'`tpid=`ps -aef | grep $tpid | awk '{print $2}' |grep $tpid`if [ ${tpid} ]; then        echo App is running.else        echo App is NOT running.fi

kill.sh

#!/bin/sh# kill -9 `ps -ef|grep 項目名稱|awk '{print $2}'`kill -9 `ps -ef|grep demo|awk '{print $2}'`

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.