Tomcat啟動分析(七) - 容器組件

本文及后續幾篇文章開始分析容器組件,它們都與請求處理息息相關,首先介紹容器組件共同的父類Container接口及ContainerBase抽象類。

容器組件

容器組件處理客戶端請求并返回響應,Tomcat中的容器組件按從高到低的順序有以下四個層次:

  • Engine:表示整個Catalina servlet引擎,可以包含一個或多個子容器,如Host或者Context等;
  • Host:表示虛擬主機,包含Context;
  • Context:表示ServletContext,包含一個或多個Wrapper;
  • Wrapper:表示單獨的servlet定義。

需要注意的是,Catalina不需要包括所有上述容器組件,所以容器組件的實現必須被設計成在沒有父容器的情況下依然可以正確運行。

Container接口

Container接口繼承了Lifecycle接口,表示Servlet容器相關組件的抽象,類層次結構如下圖所示:

Container類層次結構.png

public interface Container extends Lifecycle {
    // ----------------------------------------------------- Manifest Constants
    public static final String ADD_CHILD_EVENT = "addChild";
    public static final String ADD_VALVE_EVENT = "addValve";
    public static final String REMOVE_CHILD_EVENT = "removeChild";
    public static final String REMOVE_VALVE_EVENT = "removeValve";
    // ------------------------------------------------------------- Properties
    public Log getLogger();
    public String getLogName();
    public ObjectName getObjectName();
    public String getDomain();
    public String getMBeanKeyProperties();
    public Pipeline getPipeline();
    public Cluster getCluster();
    public void setCluster(Cluster cluster);
    public int getBackgroundProcessorDelay();
    public void setBackgroundProcessorDelay(int delay);
    public String getName();
    public void setName(String name);
    public Container getParent();
    public void setParent(Container container);
    public ClassLoader getParentClassLoader();
    public void setParentClassLoader(ClassLoader parent);
    public Realm getRealm();
    public void setRealm(Realm realm);
    // --------------------------------------------------------- Public Methods
    public void backgroundProcess();
    public void addChild(Container child);
    public void addContainerListener(ContainerListener listener);
    public void addPropertyChangeListener(PropertyChangeListener listener);
    public Container findChild(String name);
    public Container[] findChildren();
    public ContainerListener[] findContainerListeners();
    public void removeChild(Container child);
    public void removeContainerListener(ContainerListener listener);
    public void removePropertyChangeListener(PropertyChangeListener listener);
    public void fireContainerEvent(String type, Object data);
    public void logAccess(Request request, Response response, long time, boolean useDefault);
    public AccessLog getAccessLog();
    public int getStartStopThreads();
    public void setStartStopThreads(int startStopThreads);
    public File getCatalinaBase();
    public File getCatalinaHome();
}
  • 一個容器可以包含其他容器,可以通過addChild、findChild、findChildren、removeChild和setParent等接口方法進行操作;
  • 通過addContainerListener、findContainerListeners和removeContainerListener等接口方法可以向容器組件添加容器事件監聽器ContainerListener,還可以通過fireContainerEvent方法發布容器事件;
  • 通過addPropertyChangeListener和removePropertyChangeListener可以向容器組件添加屬性值改變監聽器PropertyChangeListener;
  • 注意Container接口繼承了Lifecycle接口,Lifecycle接口添加的是生命周期事件監聽器LifecycleListener,因此容器組件包含三種監聽器:生命周期事件監聽器LifecycleListener、容器事件監聽器ContainerListener和屬性值改變監聽器PropertyChangeListener。

ContainerBase抽象類

ContainerBase抽象類是Container接口的默認實現,它繼承了LifecycleBase類,同時也是其他容器組件如StandardEngine、StandardHost和StandardContext等的父類,其部分成員變量如下:

public abstract class ContainerBase extends LifecycleMBeanBase
        implements Container {
    // 省略一些代碼
    /**
     * The child Containers belonging to this Container, keyed by name.
     */
    protected final HashMap<String, Container> children = new HashMap<>();
    protected final List<ContainerListener> listeners = new CopyOnWriteArrayList<>();
    protected String name = null;
    protected Container parent = null;
    protected ClassLoader parentClassLoader = null;
    protected final Pipeline pipeline = new StandardPipeline(this);
    /**
     * The number of threads available to process start and stop events for any
     * children associated with this container.
     */
    private int startStopThreads = 1;
    protected ThreadPoolExecutor startStopExecutor;

    @Override
    public int getStartStopThreads() {
        return startStopThreads;
    }

    /**
     * Handles the special values.
     */
    private int getStartStopThreadsInternal() {
        int result = getStartStopThreads();
        // Positive values are unchanged
        if (result > 0) {
            return result;
        }
        // Zero == Runtime.getRuntime().availableProcessors()
        // -ve  == Runtime.getRuntime().availableProcessors() + value
        // These two are the same
        result = Runtime.getRuntime().availableProcessors() + result;
        if (result < 1) {
            result = 1;
        }
        return result;
    }

    @Override
    public void setStartStopThreads(int startStopThreads) {
        this.startStopThreads = startStopThreads;
        // Use local copies to ensure thread safety
        ThreadPoolExecutor executor = startStopExecutor;
        if (executor != null) {
            int newThreads = getStartStopThreadsInternal();
            executor.setMaximumPoolSize(newThreads);
            executor.setCorePoolSize(newThreads);
        }
    }
}
  • children變量是一個以子容器組件名為鍵、子容器組件自身為值的Map;
  • listeners變量保存了添加到該容器組件的容器事件監聽器,使用CopyOnWriteArrayList的原因請參見《Effective Java》第三版第79條;
  • name變量是該容器組件的名字;
  • parent變量引用該容器組件的父容器組件;
  • pipeline變量引用一個StandardPipeline,為什么要有一個Pipeline呢?從ContainerBase的類注釋可以得到答案:子類需要將自己對請求的處理過程封裝成一個Valve并通過Pipeline的setBasic方法安裝到Pipeline;
  • startStopExecutor表示啟動和停止子容器組件用的線程池,startStopThreads表示這個線程池的線程數。
  • Use local copies to ensure thread safety 這句注釋沒看明白,即使用了局部變量也是同一個引用。

組件初始化

@Override
protected void initInternal() throws LifecycleException {
    BlockingQueue<Runnable> startStopQueue = new LinkedBlockingQueue<>();
    startStopExecutor = new ThreadPoolExecutor(
            getStartStopThreadsInternal(),
            getStartStopThreadsInternal(), 10, TimeUnit.SECONDS,
            startStopQueue,
            new StartStopThreadFactory(getName() + "-startStop-"));
    startStopExecutor.allowCoreThreadTimeOut(true);
    super.initInternal();
}
  • 初始化過程為容器組件自己創建了一個線程池,該線程池用于執行子容器的啟動和停止等過程;
  • startStopExecutor里的每個線程的名稱是“容器組件名稱-startStop-”再加上線程計數,這在Tomcat啟動的日志中有所體現,如Host組件啟動時日志會有如“localhost-startStop-1”字樣的輸出。

組件啟動

@Override
protected synchronized void startInternal() throws LifecycleException {
    // 省略一些代碼
    // Start our child containers, if any
    Container children[] = findChildren();
    List<Future<Void>> results = new ArrayList<>();
    for (int i = 0; i < children.length; i++) {
        results.add(startStopExecutor.submit(new StartChild(children[i])));
    }

    boolean fail = false;
    for (Future<Void> result : results) {
        try {
            result.get();
        } catch (Exception e) {
            log.error(sm.getString("containerBase.threadedStartFailed"), e);
            fail = true;
        }

    }
    if (fail) {
        throw new LifecycleException(sm.getString("containerBase.threadedStartFailed"));
    }

    // Start the Valves in our pipeline (including the basic), if any
    if (pipeline instanceof Lifecycle)
        ((Lifecycle) pipeline).start();

    setState(LifecycleState.STARTING);
    // Start our thread
    threadStart();
}
  • 啟動過程利用初始化時創建的線程池啟動了各個子容器,如果startStopThreads大于1那么多個子容器可以并發地啟動。容器組件啟動時會等待全部的子容器組件啟動完畢,若有一個子容器啟動失敗就會拋出異常;
  • 如果有與容器組件關聯的Pipeline則啟動Pipeline;
  • 調用基類LifecycleBase的setState方法發布LifecycleState.STARTING事件給添加到容器組件自身的生命周期事件監聽器。

Pipeline組件

Pipeline組件用于封裝容器組件的請求處理過程,一般來說每個容器組件都有與其關聯的一個Pipeline。
Pipeline接口的代碼如下:

public interface Pipeline {
    public Valve getBasic();
    public void setBasic(Valve valve);
    public void addValve(Valve valve);
    public Valve[] getValves();
    public void removeValve(Valve valve);
    public Valve getFirst();
    public boolean isAsyncSupported();
    public Container getContainer();
    public void setContainer(Container container);
    public void findNonAsyncValves(Set<String> result);
}
  • getBasic、setBasic與基本閥(Basic Valve)的概念有關,Pipeline是由一系列閥(Valve)組成的鏈表,基本閥始終指向最后一個閥;
  • 基本閥封裝了容器組件對請求的處理過程,總是在一個Pipeline的末尾執行;
  • 其余的方法與鏈表操作有關,如添加、移除閥等方法。

StandardPipeline類繼承LifecycleBase類并實現了Pipeline接口,與閥有關的方法實現很簡單,在此不再贅述。initInternal方法沒有做任何事情,startInternal則依次啟動了各個實現了Lifecycle接口的閥。

@Override
protected void initInternal() {
    // NOOP
}

@Override
protected synchronized void startInternal() throws LifecycleException {
    // Start the Valves in our pipeline (including the basic), if any
    Valve current = first;
    if (current == null) {
        current = basic;
    }
    while (current != null) {
        if (current instanceof Lifecycle)
            ((Lifecycle) current).start();
        current = current.getNext();
    }

    setState(LifecycleState.STARTING);
}
  • 在看StandardPipeline類源碼的過程中需要注意basic變量永遠指向最后一個閥,first指向第一個閥。當只有一個閥時,first為null但basic不會是null,這時getFirst會返回basic而不是null。

Valve組件

Valve組件是容器組件中處理請求的組件,主要用在Pipeline中,是一種責任鏈設計模式。Tomcat內置了很多閥的實現,如前文提到的StandardEngineValve、StandardHostValve和StandardContextValve,具體可參考閥的Valve配置文檔
Valve接口的碼如下:

public interface Valve {
    public Valve getNext();
    public void setNext(Valve valve);
    public void backgroundProcess();
    public void invoke(Request request, Response response)
        throws IOException, ServletException;
    public boolean isAsyncSupported();
}
  • getNext和setNext分別獲取和設置后繼閥;
  • invoke方法處理請求,處理規約可以參考Valve API文檔
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,983評論 6 537
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,772評論 3 422
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,947評論 0 381
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,201評論 1 315
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,960評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,350評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,406評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,549評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,104評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,914評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,089評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,647評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,340評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,753評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,007評論 1 289
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,834評論 3 395
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,106評論 2 375

推薦閱讀更多精彩內容