zoukankan      html  css  js  c++  java
  • 009-tomcat源码阅读1-Lifecycle、LifecycleState、LifecycleListener、LifecycleBase、LifecycleMBeanBase

    一、概述

      Lifecycle 生命周期,在其他框架中也很常见,比如spring,它常用于具有生命周期的组件,由Lifecycle控制组件的初始化、启动、销毁等动作,方便应用程序获取、释放某些资源,或者是触发某些特定的事件。Tomcat的Catalina也提供了类似实现机制。

    二、Lifecycle

      Lifecycle接,定义了组件生命周期的方法,用于启动、停止Catalina组件。组件的生命周期包括:init、start、stop、destory,以及各种事件的常量、操作LifecycleListener的API,采用观察者模式。

    package org.apache.catalina;
    
    /**
     * Common interface for component life cycle methods.  Catalina components  may implement this interface (as well as the appropriate interface(s) for the functionality they support) 
    * in order to provide a consistent mechanism to start and stop the component. * <br> * The valid state transitions for components that support {
    @link Lifecycle} * are: * <pre> * start() * ----------------------------- * | | * | init() | * NEW -»-- INITIALIZING | * | | | | ------------------«----------------------- * | | |auto | | | * | | |/ start() |/ |/ auto auto stop() | * | | INITIALIZED --»-- STARTING_PREP --»- STARTING --»- STARTED --»--- | * | | | | | * | |destroy()| | | * | --»-----«-- ------------------------«-------------------------------- ^ * | | | | * | | |/ auto auto start() | * | | STOPPING_PREP ----»---- STOPPING ------»----- STOPPED -----»----- * | |/ ^ | ^ * | | stop() | | | * | | -------------------------- | | * | | | | | * | | | destroy() destroy() | | * | | FAILED ----»------ DESTROYING ---«----------------- | * | | ^ | | * | | destroy() | |auto | * | --------»----------------- |/ | * | DESTROYED | * | | * | stop() | * ----»-----------------------------»------------------------------ * * Any state can transition to FAILED. * * Calling start() while a component is in states STARTING_PREP, STARTING or * STARTED has no effect. * * Calling start() while a component is in state NEW will cause init() to be * called immediately after the start() method is entered. * * Calling stop() while a component is in states STOPPING_PREP, STOPPING or * STOPPED has no effect. * * Calling stop() while a component is in state NEW transitions the component * to STOPPED. This is typically encountered when a component fails to start and * does not start all its sub-components. When the component is stopped, it will * try to stop all sub-components - even those it didn't start. * * Attempting any other transition will throw {@link LifecycleException}. * * </pre> * The {@link LifecycleEvent}s fired during state changes are defined in the * methods that trigger the changed. No {@link LifecycleEvent}s are fired if the * attempted transition is not valid. * * @author Craig R. McClanahan */ public interface Lifecycle { // ----------------------------------------------------- Manifest Constants /** * The LifecycleEvent type for the "component before init" event. */ public static final String BEFORE_INIT_EVENT = "before_init"; /** * The LifecycleEvent type for the "component after init" event. */ public static final String AFTER_INIT_EVENT = "after_init"; /** * The LifecycleEvent type for the "component start" event. */ public static final String START_EVENT = "start"; /** * The LifecycleEvent type for the "component before start" event. */ public static final String BEFORE_START_EVENT = "before_start"; /** * The LifecycleEvent type for the "component after start" event. */ public static final String AFTER_START_EVENT = "after_start"; /** * The LifecycleEvent type for the "component stop" event. */ public static final String STOP_EVENT = "stop"; /** * The LifecycleEvent type for the "component before stop" event. */ public static final String BEFORE_STOP_EVENT = "before_stop"; /** * The LifecycleEvent type for the "component after stop" event. */ public static final String AFTER_STOP_EVENT = "after_stop"; /** * The LifecycleEvent type for the "component after destroy" event. */ public static final String AFTER_DESTROY_EVENT = "after_destroy"; /** * The LifecycleEvent type for the "component before destroy" event. */ public static final String BEFORE_DESTROY_EVENT = "before_destroy"; /** * The LifecycleEvent type for the "periodic" event. */ public static final String PERIODIC_EVENT = "periodic"; /** * The LifecycleEvent type for the "configure_start" event. Used by those components that use a separate component to perform configuration and * need to signal when configuration should be performed - usually after * {@link #BEFORE_START_EVENT} and before {@link #START_EVENT}. */ public static final String CONFIGURE_START_EVENT = "configure_start"; /** * The LifecycleEvent type for the "configure_stop" event. Used by those components that use a separate component to perform configuration and * need to signal when de-configuration should be performed - usually after * {@link #STOP_EVENT} and before {@link #AFTER_STOP_EVENT}. */ public static final String CONFIGURE_STOP_EVENT = "configure_stop"; // --------------------------------------------------------- Public Methods /** * Add a LifecycleEvent listener to this component. * * @param listener The listener to add */ public void addLifecycleListener(LifecycleListener listener); /** * Get the life cycle listeners associated with this life cycle. * * @return An array containing the life cycle listeners associated with this life cycle. If this component has no listeners registered, a zero-length array is returned. */ public LifecycleListener[] findLifecycleListeners(); /** * Remove a LifecycleEvent listener from this component. * * @param listener The listener to remove */ public void removeLifecycleListener(LifecycleListener listener); /** * Prepare the component for starting. This method should perform any initialization required post object creation. The following * {@link LifecycleEvent}s will be fired in the following order: * <ol> * <li>INIT_EVENT: On the successful completion of component * initialization.</li> * </ol> * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ public void init() throws LifecycleException; /** * Prepare for the beginning of active use of the public methods other than * property getters/setters and life cycle methods of this component. This * method should be called before any of the public methods other than * property getters/setters and life cycle methods of this component are * utilized. The following {@link LifecycleEvent}s will be fired in the * following order: * <ol> * <li>BEFORE_START_EVENT: At the beginning of the method. It is as this * point the state transitions to * {@link LifecycleState#STARTING_PREP}.</li> * <li>START_EVENT: During the method once it is safe to call start() for * any child components. It is at this point that the * state transitions to {@link LifecycleState#STARTING} * and that the public methods other than property * getters/setters and life cycle methods may be * used.</li> * <li>AFTER_START_EVENT: At the end of the method, immediately before it * returns. It is at this point that the state * transitions to {@link LifecycleState#STARTED}. * </li> * </ol> * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ public void start() throws LifecycleException; /** * Gracefully terminate the active use of the public methods other than * property getters/setters and life cycle methods of this component. Once * the STOP_EVENT is fired, the public methods other than property * getters/setters and life cycle methods should not be used. The following * {@link LifecycleEvent}s will be fired in the following order: * <ol> * <li>BEFORE_STOP_EVENT: At the beginning of the method. It is at this * point that the state transitions to * {@link LifecycleState#STOPPING_PREP}.</li> * <li>STOP_EVENT: During the method once it is safe to call stop() for * any child components. It is at this point that the * state transitions to {@link LifecycleState#STOPPING} * and that the public methods other than property * getters/setters and life cycle methods may no longer be * used.</li> * <li>AFTER_STOP_EVENT: At the end of the method, immediately before it * returns. It is at this point that the state * transitions to {@link LifecycleState#STOPPED}. * </li> * </ol> * * Note that if transitioning from {@link LifecycleState#FAILED} then the * three events above will be fired but the component will transition * directly from {@link LifecycleState#FAILED} to * {@link LifecycleState#STOPPING}, bypassing * {@link LifecycleState#STOPPING_PREP} * * @exception LifecycleException if this component detects a fatal error * that needs to be reported */ public void stop() throws LifecycleException; /** * Prepare to discard the object. The following {@link LifecycleEvent}s will * be fired in the following order: * <ol> * <li>DESTROY_EVENT: On the successful completion of component * destruction.</li> * </ol> * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ public void destroy() throws LifecycleException; /** * Obtain the current state of the source component. * * @return The current state of the source component. */ public LifecycleState getState(); /** * Obtain a textual representation of the current component state. Useful * for JMX. The format of this string may vary between point releases and * should not be relied upon to determine component state. To determine * component state, use {@link #getState()}. * * @return The name of the current component state. */ public String getStateName(); /** * Marker interface used to indicate that the instance should only be used * once. Calling {@link #stop()} on an instance that supports this interface * will automatically call {@link #destroy()} after {@link #stop()} * completes. */ public interface SingleUse { } }

    几乎大部分组件均实现了Lifecycle接口,

      

    • LifecycleBase:它实现了Lifecycle的init、start、stop等主要逻辑,向注册在LifecycleBase内部的LifecycleListener发出对应的事件,并且预留了initInternal、startInternal、stopInternal等模板方法,便于子类完成自己的逻辑
    • MBeanRegistration:JmxEnabled 的父类, jmx框架提供的注册MBean的接口,引入此接口是为了便于使用JMX提供的管理功能
    • LifecycleMBeanBase:JmxEnabled的子类,通过重写initInternal、destroyInternal方法,统一向jmx中注册/取消注册当前实例,方便利用jmx对实例对象进行管理,代码上特别强调要求子类先行调用super.initInternal
    • ContainerBase、StandardServer、StandardService、WebappLoader、Connector、StandardContext、StandardEngine、StandardHost、StandardWrapper等容器都继承了LifecycleMBeanBase,因此这些容器都具有了同样的生命周期并可以通过JMX进行管理

      tomcat允许我们使用jmx对tomcat进行监控、管理,可以使用jconsole工具。

    LifecycleMBeanBase 抽象类:public abstract class LifecycleMBeanBase extends LifecycleBase implements JmxEnabled

    package org.apache.catalina.util;
    
    import javax.management.InstanceNotFoundException;
    import javax.management.MBeanRegistrationException;
    import javax.management.MBeanServer;
    import javax.management.MalformedObjectNameException;
    import javax.management.ObjectName;
    
    import org.apache.catalina.Globals;
    import org.apache.catalina.JmxEnabled;
    import org.apache.catalina.LifecycleException;
    import org.apache.juli.logging.Log;
    import org.apache.juli.logging.LogFactory;
    import org.apache.tomcat.util.modeler.Registry;
    import org.apache.tomcat.util.res.StringManager;
    
    public abstract class LifecycleMBeanBase extends LifecycleBase
            implements JmxEnabled {
    
        private static final Log log = LogFactory.getLog(LifecycleMBeanBase.class);
    
        private static final StringManager sm =
            StringManager.getManager("org.apache.catalina.util");
    
    
        /* Cache components of the MBean registration. */
        private String domain = null;
        private ObjectName oname = null;
        protected MBeanServer mserver = null;
    
        /**
         * Sub-classes wishing to perform additional initialization should override
         * this method, ensuring that super.initInternal() is the first call in the
         * overriding method.
         */
        @Override
        protected void initInternal() throws LifecycleException {
            // If oname is not null then registration has already happened via
            // preRegister().
            if (oname == null) {
                mserver = Registry.getRegistry(null, null).getMBeanServer();
    
                oname = register(this, getObjectNameKeyProperties());
            }
        }
    
    
        /**
         * Sub-classes wishing to perform additional clean-up should override this
         * method, ensuring that super.destroyInternal() is the last call in the
         * overriding method.
         */
        @Override
        protected void destroyInternal() throws LifecycleException {
            unregister(oname);
        }
    
    
        /**
         * Specify the domain under which this component should be registered. Used
         * with components that cannot (easily) navigate the component hierarchy to
         * determine the correct domain to use.
         */
        @Override
        public final void setDomain(String domain) {
            this.domain = domain;
        }
    
    
        /**
         * Obtain the domain under which this component will be / has been
         * registered.
         */
        @Override
        public final String getDomain() {
            if (domain == null) {
                domain = getDomainInternal();
            }
    
            if (domain == null) {
                domain = Globals.DEFAULT_MBEAN_DOMAIN;
            }
    
            return domain;
        }
    
    
        /**
         * Method implemented by sub-classes to identify the domain in which MBeans
         * should be registered.
         *
         * @return  The name of the domain to use to register MBeans.
         */
        protected abstract String getDomainInternal();
    
    
        /**
         * Obtain the name under which this component has been registered with JMX.
         */
        @Override
        public final ObjectName getObjectName() {
            return oname;
        }
    
    
        /**
         * Allow sub-classes to specify the key properties component of the
         * {@link ObjectName} that will be used to register this component.
         *
         * @return  The string representation of the key properties component of the
         *          desired {@link ObjectName}
         */
        protected abstract String getObjectNameKeyProperties();
    
    
        /**
         * Utility method to enable sub-classes to easily register additional
         * components that don't implement {@link JmxEnabled} with an MBean server.
         * <br>
         * Note: This method should only be used once {@link #initInternal()} has
         * been called and before {@link #destroyInternal()} has been called.
         *
         * @param obj                       The object the register
         * @param objectNameKeyProperties   The key properties component of the
         *                                  object name to use to register the
         *                                  object
         *
         * @return  The name used to register the object
         */
        protected final ObjectName register(Object obj,
                String objectNameKeyProperties) {
    
            // Construct an object name with the right domain
            StringBuilder name = new StringBuilder(getDomain());
            name.append(':');
            name.append(objectNameKeyProperties);
    
            ObjectName on = null;
    
            try {
                on = new ObjectName(name.toString());
                Registry.getRegistry(null, null).registerComponent(obj, on, null);
            } catch (MalformedObjectNameException e) {
                log.warn(sm.getString("lifecycleMBeanBase.registerFail", obj, name),
                        e);
            } catch (Exception e) {
                log.warn(sm.getString("lifecycleMBeanBase.registerFail", obj, name),
                        e);
            }
    
            return on;
        }
    
    
        /**
         * Utility method to enable sub-classes to easily unregister additional
         * components that don't implement {@link JmxEnabled} with an MBean server.
         * <br>
         * Note: This method should only be used once {@link #initInternal()} has
         * been called and before {@link #destroyInternal()} has been called.
         *
         * @param on    The name of the component to unregister
         */
        protected final void unregister(ObjectName on) {
    
            // If null ObjectName, just return without complaint
            if (on == null) {
                return;
            }
    
            // If the MBeanServer is null, log a warning & return
            if (mserver == null) {
                log.warn(sm.getString("lifecycleMBeanBase.unregisterNoServer", on));
                return;
            }
    
            try {
                mserver.unregisterMBean(on);
            } catch (MBeanRegistrationException e) {
                log.warn(sm.getString("lifecycleMBeanBase.unregisterFail", on), e);
            } catch (InstanceNotFoundException e) {
                log.warn(sm.getString("lifecycleMBeanBase.unregisterFail", on), e);
            }
    
        }
    
    
        /**
         * Not used - NOOP.
         */
        @Override
        public final void postDeregister() {
            // NOOP
        }
    
    
        /**
         * Not used - NOOP.
         */
        @Override
        public final void postRegister(Boolean registrationDone) {
            // NOOP
        }
    
    
        /**
         * Not used - NOOP.
         */
        @Override
        public final void preDeregister() throws Exception {
            // NOOP
        }
    
    
        /**
         * Allows the object to be registered with an alternative
         * {@link MBeanServer} and/or {@link ObjectName}.
         */
        @Override
        public final ObjectName preRegister(MBeanServer server, ObjectName name)
                throws Exception {
    
            this.mserver = server;
            this.oname = name;
            this.domain = name.getDomain().intern();
    
            return oname;
        }
    
    }
    View Code

    Connector实现:public class Connector extends LifecycleMBeanBase

      在Tomcat架构中,Connector主要负责处理与客户端的通信。Connector的实例用于监听端口,接受来自客户端的请求并将请求转交给Engine处理。同时将来自Engine的答复返回给客户端。

    三、LifecycleState

      LifecycleState是枚举类,定义了各种状态

    public enum LifecycleState {
    
        // LifecycleBase实例化完成时的状态
        NEW(false, null),   
    
        // 容器正在初始化的状态,在INITIALIZED之前
        INITIALIZING(false, Lifecycle.BEFORE_INIT_EVENT),
    
        // 初始化完成的状态
        INITIALIZED(false, Lifecycle.AFTER_INIT_EVENT),
    
        // 启动前
        STARTING_PREP(false, Lifecycle.BEFORE_START_EVENT),
    
        // 启动过程中的状态
        STARTING(true, Lifecycle.START_EVENT),
    
        // 启动完成
        STARTED(true, Lifecycle.AFTER_START_EVENT),
    
        // 停止前的状态
        STOPPING_PREP(true, Lifecycle.BEFORE_STOP_EVENT),
    
        // 停止过程中
        STOPPING(false, Lifecycle.STOP_EVENT),
    
        // 停止完成
        STOPPED(false, Lifecycle.AFTER_STOP_EVENT),
    
        // 销毁中
        DESTROYING(false, Lifecycle.BEFORE_DESTROY_EVENT),
    
        // 完成销毁
        DESTROYED(false, Lifecycle.AFTER_DESTROY_EVENT),
    
        // 启动、停止过程中出现异常
        FAILED(false, null);
    
        private final boolean available;
        private final String lifecycleEvent;
    
        private LifecycleState(boolean available, String lifecycleEvent) {
            this.available = available;
            this.lifecycleEvent = lifecycleEvent;
        }
    
        public boolean isAvailable() {
            return available;
        }
    
        public String getLifecycleEvent() {
            return lifecycleEvent;
        }
    
    }

    四、LifecycleListener

    要订阅事件的实体类需要实现LifecycleListener

    public interface LifecycleListener {
    
        /**
         * Acknowledge the occurrence of the specified event.
         * @param event LifecycleEvent that has occurred
         */
        public void lifecycleEvent(LifecycleEvent event);
    }

    默认情况下,tomcat会内置一些LifecycleListener,配置在server.xml中,除了xml中的LifecycleListener,还有org.apache.catalina.core.NamingContextListener,而这个LifecycleListener是在StandardServer的构造器中添加的。

    server.xml配置:

      <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
      <!-- Security listener. Documentation at /docs/config/listeners.html
      <Listener className="org.apache.catalina.security.SecurityListener" />
      -->
      <!--APR library loader. Documentation at /docs/apr.html -->
      <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
      <!-- Prevent memory leaks due to use of particular java/javax APIs-->
      <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
      <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
      <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" /> 

    如果我们在tomcat启动、停止的时候增加额外的逻辑,比如发送邮件通知,则可以从这个地方入手

    五、LifecycleBase

    LifecycleBase实现了Lifecycle接口,完成了核心逻辑

    - StringManager:用来做日志信息参数化输出的,支持国际化

    - 内部使用CopyOnWriteArrayList维护所有的LifecycleListener,因为在各个生命周期,内部的LifecycleListener是会变化的,并且存在并发操作问题,因此使用了并发的List。注意,不同的LifecycleBase子类,其内部的lifecycleListeners存放不同的LifecyListener,比如Server和Service,它们是不同的Lifecycle实例,内部的lifecycleListeners也是不同

    - LifecycleBase的state初始值是LifecycleState.NEW,也存在并发修改的问题,用了volatile修饰

    - addLifecycleListener、removeLifecycleListener允许添加、删除LifecycleListener,告诉LifecycleBase有哪些监听者需要进行事件通知

    - fireLifecycleEvent:向内部注册的LifecycleListener发出事件通知,它是protected的方法,所以LifecycleBase的子类可以在适当的时机调用该方法发出事件通知。事件通知由LifecycleListener实现类决定要不要对特定的事件进行处理

    - setState:更新state值,并发出对应的事件通知,同样是调用fireLifecycleEvent

    public abstract class LifecycleBase implements Lifecycle {
    
        // 日志国际化输出使用
        private static final StringManager sm = StringManager.getManager(LifecycleBase.class);
    
        // 维护LifecycleListener
        private final List<LifecycleListener> lifecycleListeners = new CopyOnWriteArrayList<>();
    
        // 初始状态是NEW
        private volatile LifecycleState state = LifecycleState.NEW;
    
        // 注册LifecycleListener
        @Override
        public void addLifecycleListener(LifecycleListener listener) {
            lifecycleListeners.add(listener);
        }
    
        @Override
        public LifecycleListener[] findLifecycleListeners() {
            return lifecycleListeners.toArray(new LifecycleListener[0]);
        }
    
        /**
         * 移除LifecycleListener
         */
        @Override
        public void removeLifecycleListener(LifecycleListener listener) {
            lifecycleListeners.remove(listener);
        }
    
        /**
         * 发出事件通知,遍历内部所有的LifecycleListener,并调用其lifecycleEvent
         */
        protected void fireLifecycleEvent(String type, Object data) {
            LifecycleEvent event = new LifecycleEvent(this, type, data);
            for (LifecycleListener listener : lifecycleListeners) {
                listener.lifecycleEvent(event);
            }
        }
    
        @Override
        public LifecycleState getState() {
            return state;
        }
    
        @Override
        public String getStateName() {
            return getState().toString();
        }
    
        protected synchronized void setState(LifecycleState state)
                throws LifecycleException {
            setStateInternal(state, null, true);
        }
    
        protected synchronized void setState(LifecycleState state, Object data)
                throws LifecycleException {
            setStateInternal(state, data, true);
        }
    
        /**
         * 设置state值,并发出事件通知
         */
        private synchronized void setStateInternal(LifecycleState state,
                Object data, boolean check) throws LifecycleException {
    
            // 校验state的正确性
            if (check) {
                if (state == null) {
                    invalidTransition("null");
                    return;
                }
    
                // Any method can transition to failed
                // startInternal() permits STARTING_PREP to STARTING
                // stopInternal() permits STOPPING_PREP to STOPPING and FAILED to
                // STOPPING
                if (!(state == LifecycleState.FAILED ||
                        (this.state == LifecycleState.STARTING_PREP &&
                                state == LifecycleState.STARTING) ||
                        (this.state == LifecycleState.STOPPING_PREP &&
                                state == LifecycleState.STOPPING) ||
                        (this.state == LifecycleState.FAILED &&
                                state == LifecycleState.STOPPING))) {
                    // No other transition permitted
                    invalidTransition(state.name());
                }
            }
    
            this.state = state;
            String lifecycleEvent = state.getLifecycleEvent();
            if (lifecycleEvent != null) {
                fireLifecycleEvent(lifecycleEvent, data);
            }
        }
    
        // 省略其它代码......
    }

      Lifecycle组件的init、start、stop、destory的用法基本上一样,先由LifecycleBase完成前期的校验、事件通知动作,再调用子类的方法完成自己的逻辑

    六、Start分析

      start过程会触发LifecycleState的STARTING_PREP、STARTED事件,如果出现启动失败还会触发FAILED事件,并且调用stop。因为会涉及多线程操作,因此对方法加了锁。如果start期间出现了异常,则会调用stop停止tomcat,或者state状态有误也会抛出异常

      state状态变更时调用setStateInternal方法,遍历内部所有的LifecycleListener,并向其发起对应的事件通知,由LifecycleListener去完成某些动作。其子类可以直接调用fireLifecycleEvent,比如在StandardServer中,start过程会发出CONFIGURE_START_EVENT事件。注:所有事件的命名均定义在Lifecycle接口中

    直接看start 方法:

    public abstract class LifecycleBase implements Lifecycle {
        @Override
        public final synchronized void start() throws LifecycleException {
    
            // 如果是start前、进行中、start完成,则直接return
            if (LifecycleState.STARTING_PREP.equals(state) || LifecycleState.STARTING.equals(state) ||
                    LifecycleState.STARTED.equals(state)) {
                // 忽略logger日志
                return;
            }
    
            // 完成init初始化
            if (state.equals(LifecycleState.NEW)) {
                init();
            } else if (state.equals(LifecycleState.FAILED)) {
                stop();
            } else if (!state.equals(LifecycleState.INITIALIZED) &&
                    !state.equals(LifecycleState.STOPPED)) {
                invalidTransition(Lifecycle.BEFORE_START_EVENT);
            }
    
            try {
                // 发出STARTING_PREP事件
                setStateInternal(LifecycleState.STARTING_PREP, null, false);
    
                // 由子类实现
                startInternal();
    
                // 如果启动失败直接调用stop
                if (state.equals(LifecycleState.FAILED)) {
                    stop();
                } 
                // 说明状态有误
                else if (!state.equals(LifecycleState.STARTING)) {
                    invalidTransition(Lifecycle.AFTER_START_EVENT);
                } 
                // 成功完成start,发出STARTED事件
                else {
                    setStateInternal(LifecycleState.STARTED, null, false);
                }
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                setStateInternal(LifecycleState.FAILED, null, false);
                throw new LifecycleException(sm.getString("lifecycleBase.startFail", toString()), t);
            }
        }
    
        /**
         * 由子类实现
         */
        protected abstract void startInternal() throws LifecycleException;
    
    }

    七、LifecycleMBeanBase

      LifecycleMBeanBase是LifecycleBase的直接子类,并且实现了JmxEnabled接口,很多组件都是直接继承它LifecycleMBeanBase完成了jmx注册的主要逻辑,重写了LifecycleBase的initInternal、destroyInternal方法,用于完成jmx的注册、注销动作,这两个模板方法中特别说明:

         * Sub-classes wishing to perform additional initialization should override
         * this method, ensuring that super.initInternal() is the first call in the  overriding method.

      为了保证jmx的正常注册和注销,要求子类在重写initInternal、destroyInternal方法时,必须先调用super.initInternal()。例如Connector:

        @Override
        protected void initInternal() throws LifecycleException {
    
            super.initInternal();
    
            // Initialize adapter
            adapter = new CoyoteAdapter(this);
            protocolHandler.setAdapter(adapter);
            // 更多代码
            //…………
    }

      LifecycleMBeanBase的内部实现,在initInternal阶段初始化MBeanServer实例,并且把当前实例注册到jmx中;而destroyInternal阶段则是根据ObjectName注销MBean

    public abstract class LifecycleMBeanBase extends LifecycleBase
            implements JmxEnabled {
    
        /**
         * jmx的域,默认使用Service的name,即"Catalina"
         */
        private String domain = null;
    
        /**
         * 用于标识一个MBean的对象名称,也可以根据这个name来查找MBean
         */
        private ObjectName oname = null;
    
        /**
         * jmx的核心组件,提供代理端操作MBean的接口,提供了创建、注册、删除MBean的接口,它由MBeanServerFactory创建
         */
        protected MBeanServer mserver = null;
    
        @Override
        protected void initInternal() throws LifecycleException {
            if (oname == null) {
                mserver = Registry.getRegistry(null, null).getMBeanServer();
                oname = register(this, getObjectNameKeyProperties());
            }
        }
    
        @Override
        protected void destroyInternal() throws LifecycleException {
            unregister(oname);
        }
    
        protected final void unregister(ObjectName on) {
            if (on == null) {
                return;
            }
            if (mserver == null) {
                log.warn(sm.getString("lifecycleMBeanBase.unregisterNoServer", on));
                return;
            }
            try {
                mserver.unregisterMBean(on);
            } catch (MBeanRegistrationException e) {
                log.warn(sm.getString("lifecycleMBeanBase.unregisterFail", on), e);
            } catch (InstanceNotFoundException e) {
                log.warn(sm.getString("lifecycleMBeanBase.unregisterFail", on), e);
            }
    
        }
    }

    s

    转载请注明出处,感谢。
    作者:李宏旭
    阅罢此文,如果您觉得本文不错并有所收获,请【打赏】或【推荐】,也可【评论】留下您的问题或建议与我交流。
    你的支持是我不断创作和分享的不竭动力!
  • 相关阅读:
    直击美国大选,特朗普担心黑客?郭盛华这样回应
    30岁郭盛华近照曝光,容貌大变判若两人,经历了什么?
    美选举日,科技股飙升,原因是什么?
    索尼收购了TikTok?事实真是这样吗?
    腾讯手游《王者荣耀》创下每日1亿用户记录
    东方联盟创始人郭盛华十大励志名言
    抛弃谷歌!苹果研发自己的搜索引擎技术
    vivo 悟空活动中台
    Android 加载图片占用内存分析
    Linux Page Cache调优在Kafka中的应用
  • 原文地址:https://www.cnblogs.com/bjlhx/p/14349192.html
Copyright © 2011-2022 走看看