回顧一下Tomcat的啟動(dòng)步驟
- 1.安裝JDK,配置環(huán)境變量
- 2.下載Tomcat并解壓
- 3.執(zhí)行tomcat/bin目錄下的start.sh
執(zhí)行腳本后的流程
- 1.Tomcat本質(zhì)上還是一個(gè)Java程序,因此startup.sh腳本會(huì)啟動(dòng)一個(gè)JVM來(lái)運(yùn)行Tomcat的啟動(dòng)類BootStrap
其實(shí)Tomcat和我們自己平時(shí)寫的代碼并沒有本質(zhì)上的區(qū)別,只是Tomcat的啟動(dòng)時(shí)通過(guò)腳本.我們常用的SpringBoot或簡(jiǎn)單的Java類可以通過(guò)java命令啟動(dòng).
- 2.BootStrap主要任務(wù)是初始化Tomcat的
類加載器
,創(chuàng)建Catalina
. - 3.Catalina會(huì)解析server.xml,創(chuàng)建響應(yīng)的組件,并調(diào)用Server.start
- 4.Server負(fù)責(zé)管理Service,調(diào)用Service.start
- 5.Service會(huì)管理頂層容器Engine,調(diào)用Engine.start
經(jīng)過(guò)這幾步Tomcat啟動(dòng)就算完成了.
Tomcat比作公司
- Catalina:公司創(chuàng)始人,負(fù)責(zé)組件團(tuán)隊(duì),創(chuàng)建Server以及它的子組件
- Server:公司的CEO,管理多個(gè)事業(yè)群,每個(gè)事業(yè)群是一個(gè)Service
- Service:事業(yè)群總經(jīng)理,管理兩個(gè)職能部門,
對(duì)外市場(chǎng)部:連接器
,對(duì)內(nèi)的研發(fā)部:容器
- Engine:研發(fā)部總經(jīng)理,作為最頂層的容器組件
Catalina
Catalina主要任務(wù)就是創(chuàng)建Server,解析server.xml
,將server.xml定義的各個(gè)組件創(chuàng)建出來(lái),然后調(diào)用Server的init和start方法
public void start() {
//1.獲取Server,如果為空進(jìn)行創(chuàng)建
if (getServer() == null) {
load();
}
//2.創(chuàng)建失敗直接報(bào)錯(cuò)退出
if (getServer() == null) {
log.fatal(sm.getString("catalina.noServer"));
return;
}
long t1 = System.nanoTime();
// 3.啟動(dòng)Server
try {
getServer().start();
} catch (LifecycleException e) {
log.fatal(sm.getString("catalina.serverStartFail"), e);
try {
getServer().destroy();
} catch (LifecycleException e1) {
log.debug("destroy() failed for failed Server ", e1);
}
return;
}
long t2 = System.nanoTime();
if(log.isInfoEnabled()) {
log.info(sm.getString("catalina.startup", Long.valueOf((t2 - t1) / 1000000)));
}
// 創(chuàng)建Tomcat關(guān)閉的鉤子
if (useShutdownHook) {
if (shutdownHook == null) {
shutdownHook = new CatalinaShutdownHook();
}
Runtime.getRuntime().addShutdownHook(shutdownHook);
// If JULI is being used, disable JULI's shutdown hook since
// shutdown hooks run in parallel and log messages may be lost
// if JULI's hook completes before the CatalinaShutdownHook()
LogManager logManager = LogManager.getLogManager();
if (logManager instanceof ClassLoaderLogManager) {
((ClassLoaderLogManager) logManager).setUseShutdownHook(
false);
}
}
//監(jiān)聽Tomcat停止請(qǐng)求
if (await) {
await();
stop();
}
}
Hook
:鉤子,Tomcat中的關(guān)閉鉤子是用于在JVM關(guān)閉時(shí)做一些清理工作,比如將緩存數(shù)據(jù)刷到磁盤,或者清理臨時(shí)文件呢.Hook
本質(zhì)上是一個(gè)線程,JVM在停止之前會(huì)嘗試執(zhí)行這個(gè)線程的run方法.
Catalina的關(guān)閉鉤子
protected class CatalinaShutdownHook extends Thread {
@Override
public void run() {
try {
if (getServer() != null) {
//其實(shí)只是調(diào)用了stop方法
Catalina.this.stop();
}
} catch (Throwable ex) {
ExceptionUtils.handleThrowable(ex);
log.error(sm.getString("catalina.shutdownHookFail"), ex);
} finally {
//略...
}
}
}
}
Catalina的關(guān)閉Hook中,只是調(diào)用了內(nèi)部的stop
方法,最終也是通過(guò)Server的stop和destory方法進(jìn)行資源釋放和清理.
Server
Server組件的實(shí)現(xiàn)類是StandardServer
,繼承自LifeCycleBase
,生命周期被統(tǒng)一管理,它的子組件是Service,因此需要對(duì)Service的生命周期進(jìn)行管理.
- 在啟動(dòng)時(shí)調(diào)用Service組件的start方法
- 停止是調(diào)用Service組件的stop方法
Server添加Service組件
public void addService(Service service) {
service.setServer(this);
synchronized (servicesLock) {
Service results[] = new Service[services.length + 1];
System.arraycopy(services, 0, results, 0, services.length);
results[services.length] = service;
services = results;
if (getState().isAvailable()) {
try {
service.start();
} catch (LifecycleException e) {
// Ignore
}
}
// Report this property change to interested listeners
support.firePropertyChange("service", null, service);
}
}
可以看到Server通過(guò)一個(gè)數(shù)組持有所有Service的引用,同時(shí)這個(gè)數(shù)組默認(rèn)長(zhǎng)度是0,只有在每次新增Service組件時(shí)候會(huì)創(chuàng)建新的數(shù)組,長(zhǎng)度為原數(shù)組長(zhǎng)度+1,然后將原數(shù)組的數(shù)據(jù)復(fù)制到新數(shù)組中,并且使用的是System.arraycopy()
的Native方法,避免數(shù)組的自動(dòng)1.5倍擴(kuò)容浪費(fèi)內(nèi)存空間.
除了管理Service組件外,Server還有一個(gè)重要功能,就是啟動(dòng)一個(gè)Socket監(jiān)聽停止端口,就是平常使用shutdown.sh腳本就能停止的原因.
其實(shí)在Catalina啟動(dòng)的最后,有一個(gè)await
方法,這個(gè)方法就是調(diào)用了Server#await,在Server#await方法中會(huì)創(chuàng)建一個(gè)Socket對(duì)關(guān)閉進(jìn)行監(jiān)聽,在一個(gè)死循環(huán)中監(jiān)聽來(lái)自8005端口的數(shù)據(jù)(關(guān)閉端口模式就是8005),收到SHUTDOWN
指令后就會(huì)退出循環(huán),進(jìn)入stop的流程.
Service
Service的具體實(shí)現(xiàn)是StandardService
.StandardService繼承LifeCycleBase,并且會(huì)持有Server,Connector,Engine,Mapper等組件.
public class StandardService extends LifecycleBase implements Service {
//Server實(shí)例
private Server server = null;
//連接器數(shù)組
protected Connector connectors[] = new Connector[0];
private final Object connectorsLock = new Object();
//對(duì)應(yīng)的Engine容器
private Engine engine = null;
//映射器及其監(jiān)聽器
protected final Mapper mapper = new Mapper();
protected final MapperListener mapperListener = new MapperListener(this);
其中MapperListener的作用是支持動(dòng)態(tài)部署,監(jiān)聽容器變化將信息更新到Mapper中.
在Service的啟動(dòng)方法中,維護(hù)了子組件的生命周期,在各種組件啟動(dòng)的時(shí)候,組件有個(gè)字的啟動(dòng)順序
protected void startInternal() throws LifecycleException {
if(log.isInfoEnabled())
log.info(sm.getString("standardService.start.name", this.name));
//1.觸發(fā)啟動(dòng)監(jiān)聽
setState(LifecycleState.STARTING);
//2.啟動(dòng)Engine,由Engine啟動(dòng)其子容器
if (engine != null) {
synchronized (engine) {
engine.start();
}
}
//略...
//啟動(dòng)Mapper監(jiān)聽
mapperListener.start();
//最后啟動(dòng)連接器
synchronized (connectorsLock) {
for (Connector connector: connectors) {
// If it has already failed, don't try and start it
if (connector.getState() != LifecycleState.FAILED) {
connector.start();
}
}
}
}
由組件啟動(dòng)順序可以看出,Service先啟動(dòng)了Engine,然后是Mapper監(jiān)聽器,最后才啟動(dòng)連接器.
因?yàn)橹挥袑?duì)內(nèi)的組件都啟動(dòng)好了,才能啟動(dòng)對(duì)外服務(wù)的組件,這樣才能保證連接后不會(huì)因?yàn)閮?nèi)部組件未初始化完成導(dǎo)致的問(wèn)題.所以停止的順序就會(huì)和啟動(dòng)時(shí)剛好相反
Engine
Engine具體實(shí)現(xiàn)類是StandardEngine
本質(zhì)是一個(gè)頂層容器,所以會(huì)繼承自ContainerBase
,實(shí)現(xiàn)Engine接口.
但是由于Engine是頂層的容器,所以很多功能都抽象到ContainerBase
中實(shí)現(xiàn).
通過(guò)HashMap持有所有子容器Host的引用.
protected final HashMap<String, Container> children = new HashMap<>();
當(dāng)Engine在啟動(dòng)的時(shí)候,會(huì)通過(guò)專門的線程池啟動(dòng)子容器
Engine容器最重要的功能其實(shí)就是將請(qǐng)求轉(zhuǎn)發(fā)給Host進(jìn)行處理,具體是通過(guò)pipline-Valve實(shí)現(xiàn)的.
在Engine的構(gòu)造函數(shù)中,就已經(jīng)將Pipline-Valve的第一個(gè)基礎(chǔ)閥設(shè)置好了
/**
* Create a new StandardEngine component with the default basic Valve.
*/
public StandardEngine() {
super();
//設(shè)置第一個(gè)基礎(chǔ)閥
pipeline.setBasic(new StandardEngineValve());
//..略
}
StandardEngineValve
在創(chuàng)建Engine時(shí),就會(huì)默認(rèn)創(chuàng)建一個(gè)StandardEngineValve
,用于連接Host的Pipline,并且在Mapper
組件中已經(jīng)對(duì)請(qǐng)求進(jìn)行了路
由處理,通過(guò)URL定位了相應(yīng)的容器,然后把容器對(duì)象保存在Request
對(duì)象中,所以StandardEngineValve就能開始整個(gè)調(diào)用鏈路.
public final void invoke(Request request, Response response)
throws IOException, ServletException {
// Select the Host to be used for this Request
Host host = request.getHost();
if (host == null) {
// HTTP 0.9 or HTTP 1.0 request without a host when no default host
// is defined. This is handled by the CoyoteAdapter.
return;
}
if (request.isAsyncSupported()) {
request.setAsyncSupported(host.getPipeline().isAsyncSupported());
}
// Ask this Host to process this request
host.getPipeline().getFirst().invoke(request, response);
}
Server在啟動(dòng)連接器和容器都進(jìn)行了加鎖
為了保證多線程操作共享資源的正確性.
Server內(nèi)部使用了線程不安全的數(shù)組進(jìn)行Service的引用,Engine對(duì)Host的持有使用了hashMap也是線程不安全的.但是又因?yàn)榇嬖谫Y源的動(dòng)態(tài)添加和刪除,所以需要加鎖.