1. 程式人生 > 實用技巧 >How tomcat works(深入剖析tomcat)生命週期Lifecycle

How tomcat works(深入剖析tomcat)生命週期Lifecycle

How Tomcat Works (6)生命週期Lifecycle

總體概述

這一章講的是tomcat的元件之一,LifeCycle元件,通過這個元件可以統一管理其他元件,可以達到統一啟動/關閉元件的目的,那麼LifeCycle是如何實現看似如此神奇的功能的呢?

實現了LifeCycle介面的元件,可以觸發如下的事件

  • BEFORE_START_EVENT
  • START_EVENT
  • AFTER_START_EVENT
  • BEFORE_STOP_EVENT
  • STOP_EVENT
  • AFTER_STOP_EVENT

而事件監聽器LifeCycleListener,它監聽到這些事件然後做出響應的舉動,在這裡就可以去統一的開啟/關閉容器

主要類以及介面

LifeCycle介面

public interface Lifecycle {
    /**
     * The LifecycleEvent type for the "component start" event.
     */
    //start事件,其實它就是個字串
    public static final String START_EVENT = "start";
    public static final String BEFORE_START_EVENT = "before_start";
    public static final String AFTER_START_EVENT = "after_start";
    public static final String STOP_EVENT = "stop";
    public static final String BEFORE_STOP_EVENT = "before_stop";
    public static final String AFTER_STOP_EVENT = "after_stop";

    //新增Listener
    public void addLifecycleListener(LifecycleListener listener);
	//返回實現了這個介面的容器所繫結的listener
    public LifecycleListener[] findLifecycleListeners();
	//移除某個listener
    public void removeLifecycleListener(LifecycleListener listener);
	//lifecycle介面最重要的兩個方法,元件必須提供這兩個方法的實現,以供父元件呼叫,
    //實現父元件對於子元件的開啟/關閉
    public void start() throws LifecycleException;

    public void stop() throws LifecycleException;


}

LifeEvent類

生命週期事件是org.apache.catalina.LifecycleEvent類的例項,其實這個類也很簡單,對於上面的String進行了一些包裝,添加了一些額外的屬性而已,類定義如下

public final class LifecycleEvent
    extends EventObject {
    
    private Object data = null;

    private Lifecycle lifecycle = null;
	//這裡的type就對應lifecycle中定義的那6個事件
    private String type = null;
    
    public LifecycleEvent(Lifecycle lifecycle, String type) {

        this(lifecycle, type, null);

    }
    
    public LifecycleEvent(Lifecycle lifecycle, String type, Object data) {

        super(lifecycle);
        this.lifecycle = lifecycle;
        this.type = type;
        this.data = data;

    }

    public Object getData() {

        return (this.data);

    }

    public Lifecycle getLifecycle() {

        return (this.lifecycle);

    }

    public String getType() {

        return (this.type);

    }


}