理解思路 第一,抓住Standardengine的整体类依赖结构

第二:结合server.Engine配置在xml中理解
见下文具体说明。 第三,结合Engine Config官方配置文档
http://tomcat.apache.org/tomcat-9.0-doc/config/engine.html Engine接口设计设计
看看Engine.在java接口之前,请先查看相关属性 属性列表支持设置 属性 描述 backgroundProcessorDelay 这个值意味着backgroundProcess方法之间的延迟(以秒为单位)在这个引擎及其子容器(包括所有Host和Context)上调用。如果子容器的延迟值不为负(表示它们正在使用自己的处理线程),则不会调用它们。将此值设置为正值会导致生成线程。等待指定时间后,线程将在此引擎及其所有子容器上调用backgroundProcess方法。若未指定,则该属性的默认值为10,表示10秒的延迟。 className Java类名称使用。这类必须实现org.apache.catalina.Engine接口。未指定的,将使用标准值(定义如下)。 defaultHost 默认主机名称,它标记Host将处理服务器上对主机名称的要求,但在此配置文件中没有配置。这个名字必须嵌套在name中 Host元素之一的属性匹配。 jvmRoute 会话亲缘关系只有在负载平衡方案中使用的标识符才能启用。标识符(必须是参与集群的所有Tomcat服务器之间唯一的)将附加到生成的会话标识符上,因此前端代理可以始终将特定会话转发到同一Tomcat实例中。请注意,jvmroute也可以使用jvmroutesystem属性设置 。属性中的jvmRoute set
在这里,您会发现以下接口包含上述defaulthost和jvmroute属性设置;还有service,因为engine的上层是service。 /** * An Engine is a Container that represents the entire Catalina servlet * engine. It is useful in the following types of scenarios: *
- *
- You wish to use Interceptors that see every single request processed * by the entire engine. *
- You wish to run Catalina in with a standalone HTTP connector, but still * want support for multiple virtual hosts. *
* The child containers attached to an Engine are generally implementations * of Host (representing a virtual host) or Context (representing inpidual * an inpidual servlet context), depending upon the Engine implementation. *
* If used, an Engine is always the top level Container in a Catalina * hierarchy. Therefore, the implementation's setParent() method * should throw IllegalArgumentException. * * @author Craig R. McClanahan */ public interface Engine extends Container { /** * @return the default host name for this Engine. */ public String getDefaultHost(); /** * Set the default hostname for this Engine. * * @param defaultHost The new default host */ public void setDefaultHost(String defaultHost); /** * @return the JvmRouteId for this engine. */ public String getJvmRoute(); /** * Set the JvmRouteId for this engine. * * @param jvmRouteId the (new) JVM Route ID. Each Engine within a cluster * must have a unique JVM Route ID. */ public void setJvmRoute(String jvmRouteId); /** * @return the Service with which we are associated (if any). */ public Service getService(); /** * Set the Service with which we are associated (if any). * * @param service The service that owns this Engine */ public void setService(Service service); } 我们上面分析的ContainerBase中包含了其它属性支持 /** * The processor delay for this component. */ protected int backgroundProcessorDelay = -1; /** * The number of threads available to process start and stop events for any * children associated with this container. */ private int startStopThreads = 1; ... 实现Engine接口:StandardEngine 通过简单的方法实现界面
defaulthost在上述接口中, JvmRoute, service 很简单 /** * Return the default host. */ @Override public String getDefaultHost() { return defaultHost; } /** * Set the default host. * * @param host The new default host */ @Override public void setDefaultHost(String host) { String oldDefaultHost = this.defaultHost; if (host == null) { this.defaultHost = null; } else { this.defaultHost = host.toLowerCase(Locale.ENGLISH); } if (getState().isAvailable()) { service.getMapper().setDefaultHostName(host); } support.firePropertyChange("defaultHost", oldDefaultHost, this.defaultHost); } /** * Set the cluster-wide unique identifier for this Engine. * This value is only useful in a load-balancing scenario. *
* This property should not be changed once it is set. */ @Override public void setJvmRoute(String routeId) { jvmRouteId = routeId; } /** * Retrieve the cluster-wide unique identifier for this Engine. * This value is only useful in a load-balancing scenario. */ @Override public String getJvmRoute() { return jvmRouteId; } /** * Return the Service with which we are associated (if any). */ @Override public Service getService() { return this.service; } /** * Set the Service with which we are associated (if any). * * @param service The service that owns this Engine */ @Override public void setService(Service service) { this.service = service; } child, parent
addChild限制只能添加host作为子容器的重载方法;
setParent由于engine接口中已经包含了setservice方法作为其上层,而engine的上层没有容器的概念,因此直接抛出异常。 /** * Add a child Container, only if the proposed child is an implementation * of Host. * * @param child Child container to be added */ @Override public void addChild(Container child) { if (!(child instanceof Host)) throw new IllegalArgumentException (sm.getString("standardEngine.notHost")); super.addChild(child); } /** * Disallow any attempt to set a parent for this Container, since an * Engine is supposed to be at the top of the Container hierarchy. * * @param container Proposed parent Container */ @Override public void setParent(Container container) { throw new IllegalArgumentException (sm.getString("standardEngine.notParent")); } Lifecycle模板方法
只是调用上面我们介绍的ContainerBase中的方法 @Override protected void initInternal() throws LifecycleException { // Ensure that a Realm is present before any attempt is made to start // one. This will create the default NullRealm if necessary. getRealm(); super.initInternal(); } /** * Start this component 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 synchronized void startInternal() throws LifecycleException { // Log our server identification information if (log.isInfoEnabled()) { log.info(sm.getString("standardEngine.start", ServerInfo.getServerInfo())); } // Standard container startup super.startInternal(); } LogAccess
这里需要补充之前没有介绍的日志访问,这里介绍一下。
运行Web服务器时,正常生成的输出文件之一是访问日志,以标准格式为服务器处理的每个请求生成一行信息。Catalina包括一个可选的Valve,可以创建与Web服务器创建的标准格式相同的访问日志或任何数量的自定义格式。
先看xml配置; 您可以通过嵌套以下Valve元素,要求Catalina为Engine, 创建Host或Context处理的所有请求访问日志:
好了,看看具体的实现,使用适配器模式获取Acceslog类型的Valve:
以下是适配器模式:结构型 - 适配器(Adapter) @Override public AccessLog getAccessLog() { if (accessLogScanComplete) { return accessLog; } AccessLogAdapter adapter = null; Valve valves[] = getPipeline().getValves(); for (Valve valve : valves) { if (valve instanceof AccessLog) { // 看这里 if (adapter == null) { adapter = new AccessLogAdapter((AccessLog) valve); } else { adapter.add((AccessLog) valve); } } } if (adapter != null) { accessLog = adapter; } accessLogScanComplete = true; return accessLog; }
AccessLog(日志记录器)的主要功能是记录日志,这种记录方法是logAccess()方法 /** * Override the default implementation. If no access log is defined for the * Engine, look for one in the Engine's default host and then the default * host's ROOT context. If still none is found, return the default NoOp * access log. */ @Override public void logAccess(Request request, Response response, long time, boolean useDefault) { boolean logged = false; // 如果有accesslog,则记录日志 if (getAccessLog() != null) { accessLog.log(request, response, time); logged = true; } // 未找到并使用usedefault表示从下层容器中获取accesslog if (!logged && useDefault) { AccessLog newDefaultAccessLog = defaultAccessLog.get(); if (newDefaultAccessLog == null) { // If we reached this point, this Engine can't have an AccessLog // Look in the defaultHost Host host = (Host) findChild(getDefaultHost()); // 如果没有默认的acceslog,则获得默认的hostaceslog Context context = null; if (host != null && host.getState().isAvailable()) { newDefaultAccessLog = host.getAccessLog(); if (newDefaultAccessLog != null) { if (defaultAccessLog.compareAndSet(null, newDefaultAccessLog)) { AccessLogListener l = new AccessLogListener(this, host, null); l.install(); // 注册Accesslog监听器,目前Enginene } } else { // Try the ROOT context of default host context = (Context) host.findChild(""); // 如果还是找不到,获得默认host的ROT ContextaccessLog if (context != null && context.getState().isAvailable()) { newDefaultAccessLog = context.getAccessLog(); if (newDefaultAccessLog != null) { if (defaultAccessLog.compareAndSet(null, newDefaultAccessLog)) { AccessLogListener l = new AccessLogListener( this, null, context); l.install(); } } } } } if (newDefaultAccessLog == null) { newDefaultAccessLog = new NoopAccessLog(); // 这实际上是一种空模式,为了使用统一的调用方式(不需要判空) if (defaultAccessLog.compareAndSet(null, newDefaultAccessLog)) { AccessLogListener l = new AccessLogListener(this, host, context); l.install(); } } } // 最后记录日志(以上最终实现有空模式,可直接调用,无需判空) newDefaultAccessLog.log(request, response, time); } }
相关内部类别如下: protected static final class NoopAccessLog implements AccessLog { @Override public void log(Request request, Response response, long time) { // NOOP } @Override public void setRequestAttributesEnabled( boolean requestAttributesEnabled) { // NOOP } @Override public boolean getRequestAttributesEnabled() { // NOOP return false; } } protected static final class AccessLogListener implements PropertyChangeListener, LifecycleListener, ContainerListener { private final StandardEngine engine; private final Host host; private final Context context; private volatile boolean disabled = false; public AccessLogListener(StandardEngine engine, Host host, Context context) { this.engine = engine; this.host = host; this.context = context; } public void install() { engine.addPropertyChangeListener(this); if (host != null) { // 同时注册host和context同时注册 host.addContainerListener(this); host.addLifecycleListener(this); } if (context != null) { // 同时注册host和context同时注册 host.addContainerListener(this); host.addLifecycleListener(this); } if (context != null) { context.addLifecycleListener(this); } } private void uninstall() { disabled = true; if (context != null) { context.removeLifecycleListener(this); } if (host != null) { host.removeLifecycleListener(this); host.removeContainerListener(this); } engine.removePropertyChangeListener(this); } @Override public void lifecycleEvent(LifecycleEvent event) { if (disabled) return; String type = event.getType(); if (Lifecycle.AFTER_START_EVENT.equals(type) || Lifecycle.BEFORE_STOP_EVENT.equals(type) || Lifecycle.BEFORE_DESTROY_EVENT.equals(type)) { // Container is being started/stopped/removed // Force re-calculation and disable listener since it won't // be re-used engine.defaultAccessLog.set(null); uninstall(); } } @Override public void propertyChange(PropertyChangeEvent evt) { if (disabled) return; if ("defaultHost".equals(evt.getPropertyName())) { // Force re-calculation and disable listener since it won't // be re-used engine.defaultAccessLog.set(null); uninstall(); } } @Override public void containerEvent(ContainerEvent event) { // Only useful for hosts if (disabled) return; if (Container.ADD_CHILD_EVENT.equals(event.getType())) { Context context = (Context) event.getData(); if (context.getPath().isEmpty()) { // Force re-calculation and disable listener since it won't // be re-used engine.defaultAccessLog.set(null); uninstall(); } } } } JMX相关
以前有相关介绍,这里不再介绍相关方法,只列出相关方法: @Override protected String getObjectNameKeyProperties() { return "type=Engine"; } @Override protected String getDomainInternal() { return getName(); }