Spring Boot Tomcat 容器化部署實(shí)踐與總結(jié)

在平時(shí)的工作和學(xué)習(xí)中經(jīng)常會(huì)構(gòu)建簡(jiǎn)單的web應(yīng)用程序。如果只是HelloWorld級(jí)別的程序,使用傳統(tǒng)的Spring+SpringMVC框架搭建得話會(huì)將大部分的時(shí)間花費(fèi)在搭建框架本身上面,比如引入SpringMVC,配置DispatcheherServlet等。并且這些配置文件都差不多,重復(fù)這些勞動(dòng)似乎意義不大。所以使用Springboot框架來搭建簡(jiǎn)單的應(yīng)用程序顯得十分的便捷和高效。

前兩天在工作中需要一個(gè)用于測(cè)試文件下載的簡(jiǎn)單web程序,條件是使用Tomcat Docker Image作為載體,所以為了方便就使用了SpringBoot框架快速搭建起來。

程序?qū)懗鰜碓诒緳C(jī)能夠正常的跑起來,準(zhǔn)備制作鏡像,但是聞?lì)}就接踵而來了。首先是部署的問題,SpringBoot Web程序默認(rèn)打的是jar包,運(yùn)行時(shí)使用命令 java -jar -Xms128m -Xmx128m xxx.jar,本機(jī)跑的沒問題。但是需求是使用外部的tomcat容器而不是tomcat-embed,所以查閱官方文檔如下:

The first step in producing a deployable war file is to provide a SpringBootServletInitializer subclass and override its configure method. Doing so makes use of Spring Framework’s Servlet 3.0 support and lets you configure your application when it is launched by the servlet container. Typically, you should update your application’s main class to extend SpringBootServletInitializer, as shown in the following example:

@SpringBootApplication

public class Application extends SpringBootServletInitializer {

@Override

protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {

? ? return application.sources(Application.class);

}

public static void main(String[] args) throws Exception {

? ? SpringApplication.run(Application.class, args);

}

}

The next step is to update your build configuration such that your project produces a war file rather than a jar file. If you use Maven and spring-boot-starter-parent(which configures Maven’s war plugin for you), all you need to do is to modify pom.xml to change the packaging to war, as follows:

war

If you use Gradle, you need to modify build.gradle to apply the war plugin to the project, as follows:

apply plugin: 'war'

The final step in the process is to ensure that the embedded servlet container does not interfere with the servlet container to which the war file is deployed. To do so, you need to mark the embedded servlet container dependency as being provided.

If you use Maven, the following example marks the servlet container (Tomcat, in this case) as being provided:


? ? org.springframework.boot

? ? spring-boot-starter-tomcat

? ? provided


If you use Gradle, the following example marks the servlet container (Tomcat, in this case) as being provided:

dependencies {

// …

providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'

// …

}

綜上所述,將SpringBoot程序放入Tomcat運(yùn)行有兩步。第一,SpringBoot啟動(dòng)類繼承SpringBootServletInitializer,重寫configure方法。第二,將包管理軟件的打包方式改成war,并將Spring-boot-starter-tomcat設(shè)置為provided。但是,為什么應(yīng)該這么做?

根據(jù)Servlet3.0規(guī)范可知,Web容器啟動(dòng)時(shí)通過ServletContainerInitializer類實(shí)現(xiàn)第三方組件的初始化工作,如注冊(cè)servlet或filter等,每個(gè)框架要是用ServletContainerInitializer就必須在對(duì)應(yīng)的META-INF/services目錄下創(chuàng)建名為javax.servlet.ServletContainerInitializer的文件,文件內(nèi)容指定具體的ServletContainerInitializer實(shí)現(xiàn)類,在SpringMVC框架中為SpringServletContainerInitializer。一般伴隨著ServletContainerInitializer一起使用的還有HandlesTypes注解,通過HandlesTypes可以將感興趣的一些類注入到ServletContainerInitializerde的onStartup方法作為參數(shù)傳入。如下為SpringServletContainerInitializer源代碼:

@HandlesTypes(WebApplicationInitializer.class)

public class SpringServletContainerInitializer implements ServletContainerInitializer {

@Override

public void onStartup(@Nullable Set> webAppInitializerClasses, ServletContext servletContext)throws ServletException {

? ? List initializers = new LinkedList<>();

? ? if (webAppInitializerClasses != null) {

? ? ? ? for (Class waiClass : webAppInitializerClasses) {

? ? ? ? ? ? if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&

? ? ? ? ? ? ? ? ? ? WebApplicationInitializer.class.isAssignableFrom(waiClass)) {

? ? ? ? ? ? ? ? try {

? ? ? ? ? ? ? ? ? ? // 將@HandlesTypes(WebApplicationInitializer.class)標(biāo)注的所有這個(gè)類型的類都傳入到onStartup方法的Set>;為這些WebApplicationInitializer類型的類創(chuàng)建實(shí)例。

? ? ? ? ? ? ? ? ? ? initializers.add((WebApplicationInitializer)

? ? ? ? ? ? ? ? ? ? ? ? ? ? ReflectionUtils.accessibleConstructor(waiClass).newInstance());

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? catch (Throwable ex) {

? ? ? ? ? ? ? ? ? ? throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? }

? ? }

? ? if (initializers.isEmpty()) {

? ? ? ? servletContext.log("No Spring WebApplicationInitializer types detected on classpath");

? ? ? ? return;

? ? }

? ? servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");

? ? AnnotationAwareOrderComparator.sort(initializers);

? ? for (WebApplicationInitializer initializer : initializers) {

? ? ? ? //為每個(gè)WebApplicationInitializer調(diào)用自己的onStartup()

? ? ? ? initializer.onStartup(servletContext);

? ? }

}

}

SpringBootInitializer繼承WebApplicationInitializer,重寫的onStartup如下:

@Override

public void onStartup(ServletContext servletContext) throws ServletException {

this.logger = LogFactory.getLog(getClass());

? // 調(diào)用自生createRootApplicationContext()方法

WebApplicationContext rootAppContext = createRootApplicationContext(

? ? ? ? servletContext);

if (rootAppContext != null) {

? ? servletContext.addListener(new ContextLoaderListener(rootAppContext) {

? ? ? ? @Override

? ? ? ? public void contextInitialized(ServletContextEvent event) {

? ? ? ? }

? ? });

}

else {

? ? this.logger.debug("No ContextLoaderListener registered, as "

? ? ? ? ? ? + "createRootApplicationContext() did not "

? ? ? ? ? ? + "return an application context");

}

}

protected WebApplicationContext createRootApplicationContext(

? ? ? ? ServletContext servletContext) {

SpringApplicationBuilder builder = createSpringApplicationBuilder();

builder.main(getClass());

ApplicationContext parent = getExistingRootWebApplicationContext(servletContext);

if (parent != null) {

? ? this.logger.info("Root context already created (using as parent).");

? ? servletContext.setAttribute(

? ? ? ? ? ? WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null);

? ? builder.initializers(new ParentContextApplicationContextInitializer(parent));

}

builder.initializers(

? ? ? ? new ServletContextApplicationContextInitializer(servletContext));

builder.contextClass(AnnotationConfigServletWebServerApplicationContext.class);

// 調(diào)用重寫方法,重寫方法傳入SpringBoot啟動(dòng)類

builder = configure(builder);

builder.listeners(new WebEnvironmentPropertySourceInitializer(servletContext));

SpringApplication application = builder.build();

if (application.getAllSources().isEmpty() && AnnotationUtils

? ? ? ? .findAnnotation(getClass(), Configuration.class) != null) {

? ? application.addPrimarySources(Collections.singleton(getClass()));

}

Assert.state(!application.getAllSources().isEmpty(),

? ? ? ? "No SpringApplication sources have been defined. Either override the "

? ? ? ? ? ? ? ? + "configure method or add an @Configuration annotation");

if (this.registerErrorPageFilter) {

? ? application.addPrimarySources(

? ? ? ? ? ? Collections.singleton(ErrorPageFilterConfiguration.class));

}

//啟動(dòng)應(yīng)用程序,就是啟動(dòng)傳入的SpringBoot程序

return run(application);

}

在程序和Tomcat打通之后需做的就是將war打成一個(gè)Docker鏡像,如果每次都是復(fù)制war包,然后再docker build會(huì)很麻煩,在開源社區(qū)早有了解決方案–docker-maven-plugin,查看Github中的使用方法,將如下內(nèi)容加入pom.xml中:

com.spotify

docker-maven-plugin

1.1.1

? ? wanlinus/file-server





? ? ${project.basedir}


? ?

? ? ? ?

? ? ? ? ? ? /

? ? ? ? ? ? ${project.build.directory}

? ? ? ? ? ? ${project.build.finalName}.war



該配置中有個(gè)標(biāo)簽是用來指定構(gòu)建docker image的Dockerfile的位置,在項(xiàng)目的根目錄下新建一個(gè)Dockerfile,內(nèi)容如下:

FROM tomcat

MAINTAINER wanlinus

WORKDIR /docker

COPY target/file-server-0.0.1-SNAPSHOT.war ./server.war

RUN mkdir $CATALINA_HOME/webapps/server \

&& mv /docker/server.war $CATALINA_HOME/webapps/server \

&& unzip $CATALINA_HOME/webapps/server/server.war -d $CATALINA_HOME/webapps/server/ \

&& rm $CATALINA_HOME/webapps/server/server.war \

&& cd $CATALINA_HOME/webapps/server && echo "asd" > a.txt

EXPOSE 8080

終端中輸入

mvn clean package docker:build

在本地將會(huì)生成一個(gè)docker image,如果docker沒有運(yùn)行于本地,需要在標(biāo)簽中輸入遠(yuǎn)端地址和docker daemon端口。

最后在終端中運(yùn)行

docker run --rm -p 8080:8080 wanlinus/fileserver

在Tomcat啟動(dòng)后將會(huì)看到Spring Boot程序的啟動(dòng)日志,至此,Spring Boot Tomcat容器化完成。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,698評(píng)論 6 539
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,202評(píng)論 3 426
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,742評(píng)論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,580評(píng)論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,297評(píng)論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,688評(píng)論 1 327
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,693評(píng)論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,875評(píng)論 0 289
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,438評(píng)論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,183評(píng)論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,384評(píng)論 1 372
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,931評(píng)論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,612評(píng)論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,022評(píng)論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,297評(píng)論 1 292
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,093評(píng)論 3 397
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,330評(píng)論 2 377

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

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,816評(píng)論 18 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,911評(píng)論 6 342
  • 最近的國(guó)創(chuàng)項(xiàng)目需要做一個(gè)交易平臺(tái)app ,在這里把遇到的東西記錄下來。 首先找到了幾個(gè)資料,如下: 1 Andro...
    追憶__閱讀 467評(píng)論 0 0
  • 親愛的老婆: 如果給昨天晚上我們聊天下一個(gè)結(jié)論,應(yīng)該算兩個(gè)相愛的人,在夜深人靜的時(shí)候,從歷史和現(xiàn)實(shí)的角度,深刻的分...
    曉曉石頭閱讀 271評(píng)論 0 0
  • 沿著雨點(diǎn)探上 太陽光熄掉前的陰影 半響,半晌 孫陸辰 于2018.4.
    孫陸辰閱讀 157評(píng)論 0 0