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文檔
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容