当前位置: 首页 > 图灵资讯 > 技术篇> Tomcat组件管理源码详解

Tomcat组件管理源码详解

来源:图灵教育
时间:2026-04-24 16:10:42

  生命周期管理:LifeCycle

  从以下几个方面,我将帮助您构建基于上下文的知识体系,理解为什么要理解组件的生命周期管理(LifeCycle) Server及其他组件

Server后续组件的生命周期和初始化

Server依赖于结构

LifeCycle接口

  理解Lifecycle主要有两点:一是三种接口方法;二是状态机。 LifeCycle的标准方法是什么?

  分三类去看: public interface Lifecycle { /** 第一类:针对监听器 **/ // 添加监听器 public void addLifecycleListener(LifecycleListener listener); // 获得所有的监听器 public LifecycleListener[] findLifecycleListeners(); // 移除监听器 public void removeLifecycleListener(LifecycleListener listener); /** 第二类:控制过程 **/ // 初始化方法 public void init() throws LifecycleException; // 启动方法 public void start() throws LifecycleException; // 停止方法,对应start public void stop() throws LifecycleException; // 销毁方法,对应init public void destroy() throws LifecycleException; /** 第三类:针对状态 **/ // 获得生命周期状态 public LifecycleState getState(); // 获取字符串类型的生命周期状态 public String getStateName(); } LifeCycle状态机有哪些状态?

  Tomcat 定义了每个组件在生命周期中的某些状态。 在枚举类 LifecycleState 里 public enum LifecycleState { NEW(false, null), 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; } …… } 他们之间的关系是什么?

  Lifecycle.java源码中有相关注释:

  如果看不清楚,可以看下图:

LifecycleBase - LifeCycle的基本实现

  LifecycleBase是Lifecycle的基本实现。 监听器相关

  生命周期监听器保存在线程安全的copyonwritearaylist中。因此,add和remove直接调用此list的相应方法。 为了线程安全,findlifeclelisteners返回了一个数组,因此将在这里生成一个新的数组。 private final List lifecycleListeners = new CopyOnWriteArrayList<>(); @Override public void addLifecycleListener(LifecycleListener listener) { lifecycleListeners.add(listener); } @Override public LifecycleListener[] findLifecycleListeners() { return lifecycleListeners.toArray(new LifecycleListener[0]); } @Override public void removeLifecycleListener(LifecycleListener listener) { lifecycleListeners.remove(listener); } 生命周期是相关的 init @Override public final synchronized void init() throws LifecycleException { // 不允许使用init()方法进行非NEW状态 if (!state.equals(LifecycleState.NEW)) { invalidTransition(Lifecycle.BEFORE_INIT_EVENT); } try { // 在逻辑初始化之前,首先改变状态`INITIALIZING` setStateInternal(LifecycleState.INITIALIZING, null, false); // 本方法为abstract方法,初始化,要求组件自行实现 initInternal(); // 初始化完成后,状态会发生变化`INITIALIZED` setStateInternal(LifecycleState.INITIALIZED, null, false); } catch (Throwable t) { // 在初始化过程中,可能会有异常抛出,此时需要捕获异常,并将状态改为`FAILED` ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.initFail",toString()), t); } }

  让我们再来看看invalidTransition方法,它直接抛出异常。 private void invalidTransition(String type) throws LifecycleException { String msg = sm.getString("lifecycleBase.invalidTransition", type, toString(), state); throw new LifecycleException(msg); }

  setstateinternal法用于维持状态,并在状态转换成功后触发事件。为了状态的可见性,state声明为volatile类型。 private volatile LifecycleState state = LifecycleState.NEW;。 private synchronized void setStateInternal(LifecycleState state, Object data, boolean check) throws LifecycleException { if (log.isDebugEnabled()) { log.debug(sm.getString("lifecycleBase.setState", this, state)); } // 是否验证状态 if (check) { // Must have been triggered by one of the abstract methods (assume // code in this class is correct) // null is never a valid state // state不允许nullllte if (state == null) { invalidTransition("null"); // Unreachable code - here to stop eclipse complaining about // a possible NPE further down the method 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); } }

  设置完 state 状态结束后,触发该状态的事件,通知事件监听器 /** * The list of registered LifecycleListeners for event notifications. */ private final List lifecycleListeners = new CopyOnWriteArrayList<>(); protected void fireLifecycleEvent(String type, Object data) { LifecycleEvent event = new LifecycleEvent(this, type, data); for (LifecycleListener listener : lifecycleListeners) { listener.lifecycleEvent(event); } }

  这里的 LifecycleListener 对象是在 Catalina 对象解析 server.xml 已经创建并添加了文件 lifecycleListeners 里面的。这并不是特别重要,所以我就不细说了。 start @Override public final synchronized void start() throws LifecycleException { // `STARTING_PREP`、`STARTING`与`STARTED时,将忽略start()逻辑 if (LifecycleState.STARTING_PREP.equals(state) || LifecycleState.STARTING.equals(state) || LifecycleState.STARTED.equals(state)) { if (log.isDebugEnabled()) { Exception e = new LifecycleException(); log.debug(sm.getString("lifecycleBase.alreadyStarted", toString()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("lifecycleBase.alreadyStarted", toString())); } return; } // `NEW`状态时,执行init()方法 if (state.equals(LifecycleState.NEW)) { init(); } // `FAILED`执行stop()方法的状态 else if (state.equals(LifecycleState.FAILED)) { stop(); } // 不是`INITIALIZED`和`STOPPED`当时,说明是非法操作 else if (!state.equals(LifecycleState.INITIALIZED) && !state.equals(LifecycleState.STOPPED)) { invalidTransition(Lifecycle.BEFORE_START_EVENT); } try { // start前的状态设置 setStateInternal(LifecycleState.STARTING_PREP, null, false); // start逻辑,抽象方法,由组件本身实现 startInternal(); // 由于某些原因,start可能会失败,此时需要stop操作 if (state.equals(LifecycleState.FAILED)) { // This is a 'controlled' failure. The component put itself into the // FAILED state so call stop() to complete the clean-up. stop(); } else if (!state.equals(LifecycleState.STARTING)) { // Shouldn't be necessary but acts as a check that sub-classes are // doing what they are supposed to. invalidTransition(Lifecycle.AFTER_START_EVENT); } else { // STARTED设置状态为STARTED setStateInternal(LifecycleState.STARTED, null, false); } } catch (Throwable t) { // This is an 'uncontrolled' failure so put the component into the // FAILED state and throw an exception. ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException(sm.getString("lifecycleBase.startFail", toString()), t); } } stop @Override public final synchronized void stop() throws LifecycleException { // `STOPPING_PREP`、`STOPPING`与STOPPED时,stop()执行将被忽略 if (LifecycleState.STOPPING_PREP.equals(state) || LifecycleState.STOPPING.equals(state) || LifecycleState.STOPPED.equals(state)) { if (log.isDebugEnabled()) { Exception e = new LifecycleException(); log.debug(sm.getString("lifecycleBase.alreadyStopped", toString()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("lifecycleBase.alreadyStopped", toString())); } return; } // `NEW`当状态直接改变时,状态直接改变`STOPPED` if (state.equals(LifecycleState.NEW)) { state = LifecycleState.STOPPED; return; } // stop()执行必须是`STARTED`和`FAILED` if (!state.equals(LifecycleState.STARTED) && !state.equals(LifecycleState.FAILED)) { invalidTransition(Lifecycle.BEFORE_STOP_EVENT); } try { // `FAILED`时,BEFORE直接触发STOP_EVENT事件 if (state.equals(LifecycleState.FAILED)) { // Don't transition to STOPPING_PREP as that would briefly mark the // component as available but do ensure the BEFORE_STOP_EVENT is // fired fireLifecycleEvent(BEFORE_STOP_EVENT, null); } else { // STOPPING_设置状态PREP setStateInternal(LifecycleState.STOPPING_PREP, null, false); } // stop逻辑,抽象方法,自行实现组件 stopInternal(); // Shouldn't be necessary but acts as a check that sub-classes are // doing what they are supposed to. if (!state.equals(LifecycleState.STOPPING) && !state.equals(LifecycleState.FAILED)) { invalidTransition(Lifecycle.AFTER_STOP_EVENT); } // STOPPED设置状态 setStateInternal(LifecycleState.STOPPED, null, false); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException(sm.getString("lifecycleBase.stopFail",toString()), t); } finally { if (this instanceof Lifecycle.SingleUse) { // Complete stop process first setStateInternal(LifecycleState.STOPPED, null, false); destroy(); } } } destory @Override public final synchronized void destroy() throws LifecycleException { // `FAILED`状态时,stop()逻辑直接触发 if (LifecycleState.FAILED.equals(state)) { try { // Triggers clean-up stop(); } catch (LifecycleException e) { // Just log. Still want to destroy. log.warn(sm.getString( "lifecycleBase.destroyStopFail", toString()), e); } } // `DESTROYING`和`DESTROYED`时,忽略destroy执行 if (LifecycleState.DESTROYING.equals(state) || LifecycleState.DESTROYED.equals(state)) { if (log.isDebugEnabled()) { Exception e = new LifecycleException(); log.debug(sm.getString("lifecycleBase.alreadyDestroyed", toString()), e); } else if (log.isInfoEnabled() && !(this instanceof Lifecycle.SingleUse)) { // Rather than have every component that might need to call // destroy() check for SingleUse, don't log an info message if // multiple calls are made to destroy() log.info(sm.getString("lifecycleBase.alreadyDestroyed", toString())); } return; } // 判断非法状态 if (!state.equals(LifecycleState.STOPPED) && !state.equals(LifecycleState.STOPPED) && !state.equals(LifecycleState.FAILED) && !state.equals(LifecycleState.NEW) && !state.equals(LifecycleState.INITIALIZED)) { invalidTransition(Lifecycle.BEFORE_DESTROY_EVENT); } try { // 设置destroy前状态 setStateInternal(LifecycleState.DESTROYING, null, false); // 抽象方法,自行实现组件 destroyInternal(); // destroy后状态设置 setStateInternal(LifecycleState.DESTROYED, null, false); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); setStateInternal(LifecycleState.FAILED, null, false); throw new LifecycleException( sm.getString("lifecycleBase.destroyFail",toString()), t); } } 设计模式是什么?

  从上面的源代码可以看出,LifecycleBase是用状态机+模板模式来实现的。模板方法如下: // 初始化方法 protected abstract void initInternal() throws LifecycleException; // 启动方法 protected abstract void startInternal() throws LifecycleException; // 停止方法 protected abstract void stopInternal() throws LifecycleException; // 销毁方法 protected abstract void destroyInternal() throws LifecycleException; 组件扩展管理:MX和MBean 了解JMX的原因

  当我们在上面讨论Lifecycle和相关组件时,你会发现左边的JMX和MBean实现了另一个设计,即LifecycleMBeanBase。.

什么是JMX和MBean?

  JMX是Java1.5中引入的新特性。JMX全称为“Java Management Extension即Java管理扩展。

  JMX(Java Management Extensions)它是一个为应用程序植入管理功能的框架。JMX是一套标准的代理和服务。事实上,用户可以在任何Java应用程序中使用这些代理和服务来实现管理。它使用最简单的Javabean和著名的MBean,其中包含数据信息,可能是程序配置信息、模块信息、系统信息、统计信息等。MBean可以操作可读可写属性,并直接操作某些函数。

  应用场景:中间件软件Weblogic的管理页面是基于JMX开发的,而JBOSS则是基于JMX框架的整个系统,我们今天谈论的Tomcat也是基于JMX开发的。

  让我们看看JMX的结构

Probe Level 负责资源检测(获取信息),包括MBeans,通常也称为Instrumentatiiiion Level。MX管理构件(MBean)分为标准管理构件四种形式(Standard MBean)、构件的动态管理(Dynamic MBean)、开放管理部件(Open Mbean)以及模型管理部件(Model MBean)。 The Agent Level 或者叫MBean Server(代理服务器)是JMX的核心,连接Mbeans和远程监控程序。 Remote Management Level MBeanennectors和adaptors通过conectors远程操作 Server。 使用JMX案例

  上一节只是介绍了相关的概念,这还不够,你还需要一个案例来帮助你了解JMX是如何工作的。 基于JMX的监控例子 ServerImpl - 我们模拟的服务器ServerImpl状态 public class ServerImpl { public final long startTime; public ServerImpl() { startTime = System.currentTimeMillis(); } } 由于MXBean规定标准MBean也应该实现一个接口,所有向外界公开的方法都应该在接口中说明,否则管理系统无法获取信息。此外,该接口的命名有一定的规范:在标准MBean类名后添加MBean后缀。这里的标准MBean类是ServerMonitor,因此相应的接口应该是ServerMonitorMBean。因此,ServerMonitorMBean的实现如下 public interface ServerMonitorMBean { public long getUpTime(); } 利用ServerMonitor类来监控Serverimpl的状态,实现以下几点 public class ServerMonitor implements ServerMonitorMBean { private final ServerImpl target; public ServerMonitor(ServerImpl target) { this.target = target; } @Override public long getUpTime() { return System.currentTimeMillis() - target.startTime; } } 对于管理系统来说,这些MBean中公开的方法最终会被JMX转换为属性(Attribute)、监听(Listener)和调用(Invoke)概念。Mainmanage方法在下面的代码中模拟了管理程序是如何获得监控属性并显示监控结果的。 import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; public class Main { private static ObjectName objectName; private static MBeanServer mBeanServer; public static void main(String[] args) throws Exception { init(); manage(); } private static void init() throws Exception { ServerImpl serverImpl = new ServerImpl(); ServerMonitor serverMonitor = new ServerMonitor(serverImpl); mBeanServer = MBeanServerFactory.createMBeanServer(); objectName = new ObjectName("objectName:id=ServerMonitor1; // MBeanServer注册 mBeanServer.registerMBean(serverMonitor, objectName); } private static void manage() throws Exception { // 获取属性值 long upTime = (Long)mBeanServer.getAttribute(objectName, "UpTime"); System.out.println(upTime); } } 整体流程

  以上步骤可以让您了解Jconsole是如何通过JMX获取属性、对象等监控信息的。 基于JMX的HTMLAdapter案例

  上面的例子还没有反映adapter的显示,比如上面的信息在HTML页面上显示,再看一个例子 我们的管理目标 public class ControlTarget { private long width; private long length; public ControlTarget( long width, long length) { this.width = width; this.length = length; } public long getWidth() { return width; } public long getLength() { return length; } } 根据标准MBean抽象符合标准的MBean接口,修改标准MBean接口。 public interface ControlImplMBean { public long getLength(); public long getWidth(); public long getArea(); public double getLengthWidthRatio(); } 根据需要,创建管理(目标程序)类别,包括操作和获取(目标程序)特征的方法。这个类别是标准MBean类别。 public class ControlImpl implements ControlImplMBean { private ControlTarget target; public ControlImpl(ControlTarget target) { this.target = target; } @Override public long getLength() { return target.getLength(); } @Override public long getWidth() { return target.getWidth(); } @Override public long getArea() { return target.getLength() * target.getWidth(); } @Override public double getLengthWidthRatio() { return target.getLength() * 1.0f / target.getWidth(); } } 创建MBean的代理类别包括创建MBeanServer、ObjectName、注册MBean、MBean的表现 import com.sun.jdmk.comm.HtmlAdaptorServer; import javax.management.*; public class ControlImplAgent { public static void main(String[] args) throws MalformedObjectNameException, NullPointerException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { // 创建MBeanServer MBeanServer server = MBeanServerFactory.createMBeanServer(); // 为MBean创建ObjectName ObjectName controlImplName = new ObjectName("controlImpl:name=firstOne"); // 在Server中注册MBean server.registerMBean(new ControlImpl(new ControlTarget(50, 200)), controlImplName); // 表现MBean(一种方式) ObjectName adapterName = new ObjectName("ControlImpl:name=htmladapter,port=8082"); HtmlAdaptorServer adapter = new HtmlAdaptorServer(); server.registerMBean(adapter, adapterName); adapter.start(); //adapter.stop(); } } 打开相关页面

  PS:相关Adapter可以在此下载https://download.csdn.net/download/com_ma/10379741

  点击最后一个链接

Tomcat如何通过JMX实现组件管理?

  在简单理解了JMX的概念和案例之后,我们就可以开始学习基于JMX的Tomcat的实现。

  在上图中,我们来看看相关类别的用途。

  MBeanRegistration:Java 为使用JMX提供的管理功能,JMX框架提供的注册MBean接口被引入;

  JmxEnabled: 该接口由组件实现。这些组件将在创建时注册为MBean服务器,并在销毁时注销。它主要是由实现生命周期的组件实现的,但不是专门为它们实现的。

  LifecycleMBeanBase:Tomcat提供的MBeanregistration抽象实现类,使用抽象模板模式将所有容器注册到JMX;

  此外,ContainerBase、StandardServer、StandardService、WebappLoader、Connector、StandardContext、StandardEngine、StandardHost、StandardWraper等容器都继承了LifecycleMBeanbase,所以这些容器都有相同的生命周期,可以通过JMX管理。 MBeanRegistration

  理解MBeanregistration主要在于: 两块内容:registered 和 unregistered 两种方法:before和after public interface MBeanRegistration { // 注册前执行的方法,如有异常,MBean不会注册到MBean Server中 public ObjectName preRegister(MBeanServer server, ObjectName name) throws java.lang.Exception; // 注册后执行的方法,例如,注册失败提供错信息 public void postRegister(Boolean registrationDone); // 卸载前执行的方法 public void preDeregister() throws java.lang.Exception ; // 卸载后的方法执行 public void postDeregister(); } JmxEnabled

  理解JmxEnabled:它在设计上引用了一个域(Domain)隔离注册MBeans,类似于MBean上层的命名空间。 public interface JmxEnabled extends MBeanRegistration { // 获取MBean属于的Domain String getDomain(); // 设置Domain void setDomain(String domain); // 获取MBean名称的MBean ObjectName getObjectName(); } LifecycleMBeanBase

  当你理解LifecycleMBeanBase时,你就会知道它包含两个部分,一个是Lifecycle接口实现,另一个是Jmx接口封装实现。

  从其实现的类继承与关系可以看出: public abstract class LifecycleMBeanBase extends LifecycleBase implements JmxEnabled { } 实现Jmxenabled接口 与mbeannnname相关的Domain代码非常简单,没有详细说明 /* Cache components of the MBean registration. */ private String domain = null; private ObjectName oname = null; @Deprecated protected MBeanServer mserver = null; /** * 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. *
* 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. *
* Note: This method should only be used once {@link #initInternal()} has * been called and before {@link #destroyInternal()} has been called. * * @param objectNameKeyProperties The key properties component of the * object name to use to unregister the * object */ protected final void unregister(String objectNameKeyProperties) { // Construct an object name with the right domain StringBuilder name = new StringBuilder(getDomain()); name.append(':'); name.append(objectNameKeyProperties); Registry.getRegistry(null, null).unregisterComponent(name.toString()); } /** * Utility method to enable sub-classes to easily unregister additional * components that don't implement {@link JmxEnabled} with an MBean server. *
* 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) { Registry.getRegistry(null, null).unregisterComponent(on); } /** * 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; } Lifecyclebase相关界面

  这样你就知道以下两种抽象LifecycleBase方法的目的,即注册和卸载MBean /** 注册MBean */ @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()); } } /** 卸载MBean */ @Override protected void destroyInternal() throws LifecycleException { unregister(oname); }