理解思路 第一:类比StandardServer, 抓住StandardService的整体类依赖结构

第二:结合server.理解xml中service配置
见下文具体说明。 第三,与Service相结合 Config官方配置文档
http://tomcat.apache.org/tomcat-9.0-doc/config/service.html Service结构设计
我们需要从更高的维度来理解service的结构设计,而不是多少方法和代码;这里的理解必须与server相结合.service配置在xml中的对应理解。 server.xml 首先要看server.Service在xml中的配置,让你知道需要知道的四个部分 Server with which we are associated (if any). */ public Server getServer(); /** * Set the Server with which we are associated (if any). * * @param server The server that owns this Service */ public void setServer(Server server); /** * @return the parent class loader for this component. If not set, return * {@link #getServer()} {@link Server#getParentClassLoader()}. If no server * has been set, return the system class loader. */ public ClassLoader getParentClassLoader(); /** * Set the parent class loader for this service. * * @param parent The new parent class loader */ public void setParentClassLoader(ClassLoader parent); /** * @return the domain under which this container will be / has been * registered. */ public String getDomain(); connector相关Connector /** * Add a new Connector to the set of defined Connectors, and associate it * with this Service's Container. * * @param connector The Connector to be added */ public void addConnector(Connector connector); /** * Find and return the set of Connectors associated with this Service. * * @return the set of associated Connectors */ public Connector[] findConnectors(); /** * Remove the specified Connector from the set associated from this * Service. The removed Connector will also be disassociated from our * Container. * * @param connector The Connector to be removed */ public void removeConnector(Connector connector); Engine /** * @return the Engine that handles requests for all * Connectors associated with this Service. */ public Engine getContainer(); /** * Set the Engine that handles requests for all * Connectors associated with this Service. * * @param engine The new Engine */ public void setContainer(Engine engine); Excutor相关 /** * Adds a named executor to the service * @param ex Executor */ public void addExecutor(Executor ex); /** * Retrieves all executors * @return Executor[] */ public Executor[] findExecutors(); /** * Retrieves executor by name, null if not found * @param name String * @return Executor */ public Executor getExecutor(String name); /** * Removes an executor from the service * @param ex Executor */ public void removeExecutor(Executor ex); StandardService的实现
与父Server相关的属性相对简单,这里主要看其他方法: Engine相关 private Engine engine = null; @Override public Engine getContainer() { return engine; } @Override public void setContainer(Engine engine) { Engine oldEngine = this.engine; if (oldEngine != null) { oldEngine.setService(null); } this.engine = engine; if (this.engine != null) { this.engine.setService(this); } if (getState().isAvailable()) { if (this.engine != null) { try { this.engine.start(); // 启动Engine } catch (LifecycleException e) { log.error(sm.getString("standardService.engine.startFailed"), e); } } // 重启Mapper - Restart MapperListener to pick up new engine. try { mapperListener.stop(); } catch (LifecycleException e) { log.error(sm.getString("standardService.mapperListener.stopFailed"), e); } try { mapperListener.start(); } catch (LifecycleException e) { log.error(sm.getString("standardService.mapperListener.startFailed"), e); } if (oldEngine != null) { try { oldEngine.stop(); } catch (LifecycleException e) { log.error(sm.getString("standardService.engine.stopFailed"), e); } } } // 触发container属性变化 support.firePropertyChange("container", oldEngine, this.engine); } 与Connectors相关的conectors /** * The set of Connectors associated with this Service. */ protected Connector connectors[] = new Connector[0]; private final Object connectorsLock = new Object(); /** * Add a new Connector to the set of defined Connectors, and associate it * with this Service's Container. * * @param connector The Connector to be added */ @Override public void addConnector(Connector connector) { synchronized (connectorsLock) { connector.setService(this); Connector results[] = new Connector[connectors.length + 1]; System.arraycopy(connectors, 0, results, 0, connectors.length); results[connectors.length] = connector; connectors = results; } try { if (getState().isAvailable()) { connector.start(); } } catch (LifecycleException e) { throw new IllegalArgumentException( sm.getString("standardService.connector.startFailed", connector), e); } // Report this property change to interested listeners support.firePropertyChange("connector", null, connector); } public ObjectName[] getConnectorNames() { ObjectName results[] = new ObjectName[connectors.length]; for (int i=0; i
CRUD方法,代码简单 /** * Adds a named executor to the service * @param ex Executor */ @Override public void addExecutor(Executor ex) { synchronized (executors) { if (!executors.contains(ex)) { executors.add(ex); if (getState().isAvailable()) { try { ex.start(); // 启动 } catch (LifecycleException x) { log.error(sm.getString("standardService.executor.start"), x); } } } } } /** * Retrieves all executors * @return Executor[] */ @Override public Executor[] findExecutors() { synchronized (executors) { Executor[] arr = new Executor[executors.size()]; executors.toArray(arr); return arr; } } /** * Retrieves executor by name, null if not found * @param executorName String * @return Executor */ @Override public Executor getExecutor(String executorName) { synchronized (executors) { for (Executor executor: executors) { if (executorName.equals(executor.getName())) return executor; } } return null; } /** * Removes an executor from the service * @param ex Executor */ @Override public void removeExecutor(Executor ex) { synchronized (executors) { if ( executors.remove(ex) && getState().isAvailable() ) { try { ex.stop(); // 停止 } catch (LifecycleException e) { log.error(sm.getString("standardService.executor.stop"), e); } } } } Lifecycle相关模板方法
首先看 initInternal 方法 /** * Invoke a pre-startup initialization. This is used to allow connectors * to bind to restricted ports under Unix operating environments. */ @Override protected void initInternal() throws LifecycleException { super.initInternal(); if (engine != null) { engine.init(); } // Initialize any Executors for (Executor executor : findExecutors()) { if (executor instanceof JmxEnabled) { ((JmxEnabled) executor).setDomain(getDomain()); } executor.init(); } // Initialize mapper listener mapperListener.init(); // Initialize our defined Connectors synchronized (connectorsLock) { for (Connector connector : connectors) { connector.init(); } } }
initInternal 代码很短,思路也很清晰,就是这个成员变量依次调用。 init 方法 engine.init() executor.init mapperListener.init() connector.init()
startInternal 方法 /** * Start nested components ({@link Executor}s, {@link Connector}s and * {@link Container}s) and implement the requirements of * {@link org.apache.catalina.util.LifecycleBase#startInternal()}. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ @Override protected void startInternal() throws LifecycleException { if(log.isInfoEnabled()) log.info(sm.getString("standardService.start.name", this.name)); setState(LifecycleState.STARTING); // Start our defined Container first if (engine != null) { synchronized (engine) { engine.start(); } } synchronized (executors) { for (Executor executor: executors) { executor.start(); } } mapperListener.start(); // Start our defined Connectors second synchronized (connectorsLock) { for (Connector connector: connectors) { // If it has already failed, don't try and start it if (connector.getState() != LifecycleState.FAILED) { connector.start(); } } } }
startInternal 跟 initInternal 方法相同,依次调用 engine.start(); executor.start(); mapperListener.start(); connector.start(); 补充Mapperlistener
mapperListener 的作用是在 start 将容器类对象注册到 Mapper 对象中。 /** * Create mapper listener. * * @param service The service this listener is associated with */ public MapperListener(Service service) { this.service = service; this.mapper = service.getMapper(); } service.getMapper() 返回的是 StandardService 对象的 mapper 成员变量。 /** * Mapper. */ protected final Mapper mapper = new Mapper();
Mapper是 Tomcat 处理 Http 要求时非常重要的组件。Tomcat 使用 Mapper 来处理一个 Request 到 Host、Context 从而决定使用哪种映射关系 Service 处理请求。
MapperListener 也是继承自 LifecycleMBeanBase,但是没有重载 initInternal 方法。 startInternal 方法 @Override public void startInternal() throws LifecycleException { setState(LifecycleState.STARTING); Engine engine = service.getContainer(); if (engine == null) { return; } findDefaultHost(); addListeners(engine); Container[] conHosts = engine.findChildren(); for (Container conHost : conHosts) { Host host = (Host) conHost; if (!LifecycleState.NEW.equals(host.getState())) { // Registering the host will register the context and wrappers registerHost(host); } } } findDefaultHost() 方法
首先看 findDefaultHost() 方法 private void findDefaultHost() { Engine engine = service.getContainer(); String defaultHost = engine.getDefaultHost(); boolean found = false; if (defaultHost != null && defaultHost.length() > 0) { Container[] containers = engine.findChildren(); for (Container container : containers) { Host host = (Host) container; if (defaultHost.equalsIgnoreCase(host.getName())) { found = true; break; } String[] aliases = host.findAliases(); for (String alias : aliases) { if (defaultHost.equalsIgnoreCase(alias)) { found = true; break; } } } } if (found) { mapper.setDefaultHostName(defaultHost); } else { log.error(sm.getString("mapperListener.unknownDefaultHost", defaultHost, service)); } }
findDefaultHost() 主要是找出 defaultHost ,并调用 mapper.setDefaultHostName(defaultHost); 这个 defaultHost 是 server.xml 的
从上面代码 for 在代码块中可以看到,Host 是 Engine 的子 Container。for 语句就是找一个名字和一个名字 defaultHost 指定的名称相同 Host 对象。 addListeners(engine) 方法 /** * Add this mapper to the container and all child containers * * @param container */ private void addListeners(Container container) { container.addContainerListener(this); container.addLifecycleListener(this); for (Container child : container.findChildren()) { addListeners(child); } }
这种方法的作用是,将 MapperListener 添加了这个监听器 Engine 及其子容器 registerHost 调用 registerHost方法注册 Engine 的字容器 Host。 /** * Register host. */ private void registerHost(Host host) { String[] aliases = host.findAliases(); mapper.addHost(host.getName(), aliases, host); for (Container container : host.findChildren()) { if (container.getState().isAvailable()) { registerContext((Context) container); } } // Default host may have changed findDefaultHost(); if(log.isDebugEnabled()) { log.debug(sm.getString("mapperListener.registerHost", host.getName(), domain, service)); } }
registerHost 方法先调用 mapper.addHost,然后调用 registerContext 方法注册 Host 的子容器 Context。 mapper.addHost 方法是将 Host 加入的 Mapper 成员变量MappedHost[] hosts 中。
接着看 registerContext 方法 /** * Register context. */ private void registerContext(Context context) { String contextPath = context.getPath(); if ("/".equals(contextPath)) { contextPath = ""; } Host host = (Host)context.getParent(); WebResourceRoot resources = context.getResources(); String[] welcomeFiles = context.findWelcomeFiles(); List
registerContext 先得到一些对象,比如 WebResourceRoot 对象、WrapperMappingInfo 对象,然后调用 mapper.addContextVersion。
Mapper#addContextVersion 方法比较琐碎,就不细说了。
其主要逻辑是将军 Context 对象,以及 Context 的子容器 Wrapper 对象,每个对象都分别构建相应的对象 MappedContext 和 MappedWrapper 对象,
然后把 MappedContext 和 MappedWrapper 塞进 ContextVersion 对象中,
最后把 Context 和 ContextVersion 相应的关系放在 Mapper 对象的一个 Map 里。
这里的 MappedContext 和 MappedWrapper 在 Tomcat 处理 Http 要求更为关键。
registerHost 最后更新了可能发生的变化。 defaultHost。