当前位置: 首页 > 图灵资讯 > 技术篇> Tomcat Container的管道机制:责任链模式

Tomcat Container的管道机制:责任链模式

来源:图灵教育
时间:2026-05-07 20:37:35

  内容引入

  承接以上Engine的设计,我将从以下几个方面向您解释为什么要了解Tomcat中的管道机制,它需要解决哪些问题? Pipeline和Vavle在Tomcat总架构图中

在上面的Engine中,我们有一个Pipline没有解释:

Tomcat为何要引入Pipline?它需要解决哪些问题?

  下面将向您详细介绍。 知识准备

  在了解管道机制之前,您需要一些基本知识和其他软件设计中的应用场景。 责任链模式

  在设计模式上,管道机制属于责任链模式,如您不了解,请参阅以下文章:

  责任链模式(Chain of responsibility pattern): 采用责任链模式, 你可以为某个请求创建一个对象链. 每个对象按顺序检查此请求并处理它,或将其传递给链中的下一个对象。 FilterChain

  FilterChain是软件开发中常见的责任链模式,它体现在许多软件设计中: 比如Spring Security框架

例如,在Httpservletrequest处理的过滤器中

  当一个request过来时,需要对这个request进行一系列的处理。使用责任链模式可以使每个处理组件化,减少耦合。也可以用在request过来的时候,需要找到合适的处理方法。当一种处理方法不适合request时,将其传递到下一种处理方法,然后尝试request处理。

  我们在网上找到了图片,这里我们将通过Tomcat请求处理向您解释。

Pipline机制

  为什么要有管道机制?

  在一个复杂的大系统中,如果对象或数据流需要复杂的逻辑处理,我们可以选择直接处理这些复杂的业务逻辑在一个大组件中, 虽然这种方法达到了目的,但扩展性和可重用性较差, 因为它可能会移动整个身体。更好的解决方案是使用管道机制,用一根管道连接多个对象(阀门部件),整体看起来像嵌入在管道中的几个阀门,处理逻辑放在阀门上。 Vavle接口设计

  了解其设计的第一步是阀门设计 public interface Valve { // 有nexttt,因为它需要传递给下一个Valve处理,所以 public Valve getNext(); public void setNext(Valve valve); // 该方法易于执行周期任务,如重新加载组件。该方法将在容器类加载的上下文中调用。 public void backgroundProcess(); // 这种方法很容易理解。将处理阀中的执行方法传入Request和Response进行处理 public void invoke(Request request, Response response) throws IOException, ServletException; // 这个阀门支持Servletet吗? 3+ 异步的请求 public boolean isAsyncSupported(); } Pipline接口设计设计

  由于Pipline是为容器设计的,因此在设计中增加了一个Containerd接口, 目前Pipline所属的容器是制定的: public interface Contained { Container getContainer(); void setContainer(Container container); }

  让我们来看看Pipline接口设计 public interface Pipeline extends Contained { // 基础处理阀 public Valve getBasic(); public void setBasic(Valve valve); // 添加和删除节点(阀门) public void addValve(Valve valve); public Valve[] getValves(); public void removeValve(Valve valve); // 获取第一个节点,遍历的起点,所以需要有这种方法 public Valve getFirst(); // Servlet3异步处理是否支持所有节点(阀门) public boolean isAsyncSupported(); // 找到所有不支持Servlet3异步处理的阀门 public void findNonAsyncValves(Set result); } Basevavl设计

  因为Valve也是一个组件,需要生命周期管理,所以LifecycleMBeanbase同时集成了Contained和Valve public abstract class ValveBase extends LifecycleMBeanBase implements Contained, Valve { protected static final StringManager sm = StringManager.getManager(ValveBase.class); //------------------------------------------------------ Constructor public ValveBase() { this(false); } public ValveBase(boolean asyncSupported) { this.asyncSupported = asyncSupported; } //------------------------------------------------------ Instance Variables /** * Does this valve support Servlet 3+ async requests? */ protected boolean asyncSupported; /** * The Container whose pipeline this Valve is a component of. */ protected Container container = null; /** * Container log */ protected Log containerLog = null; /** * The next Valve in the pipeline this Valve is a component of. */ protected Valve next = null; //-------------------------------------------------------------- Properties /** * Return the Container with which this Valve is associated, if any. */ @Override public Container getContainer() { return container; } /** * Set the Container with which this Valve is associated, if any. * * @param container The new associated container */ @Override public void setContainer(Container container) { this.container = container; } @Override public boolean isAsyncSupported() { return asyncSupported; } public void setAsyncSupported(boolean asyncSupported) { this.asyncSupported = asyncSupported; } /** * Return the next Valve in this pipeline, or null if this * is the last Valve in the pipeline. */ @Override public Valve getNext() { return next; } /** * Set the Valve that follows this one in the pipeline it is part of. * * @param valve The new next valve */ @Override public void setNext(Valve valve) { this.next = valve; } //---------------------------------------------------------- Public Methods /** * Execute a periodic task, such as reloading, etc. This method will be * invoked inside the classloading context of this container. Unexpected * throwables will be caught and logged. */ @Override public void backgroundProcess() { // NOOP by default } @Override protected void initInternal() throws LifecycleException { super.initInternal(); containerLog = getContainer().getLogger(); } /** * 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 { setState(LifecycleState.STARTING); } /** * Stop this component and implement the requirements * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ @Override protected synchronized void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); } /** * Return a String rendering of this object. */ @Override public String toString() { return ToStringUtil.toString(this); } // -------------------- JMX and Registration -------------------- @Override public String getObjectNameKeyProperties() { StringBuilder name = new StringBuilder("type=Valve"); Container container = getContainer(); name.append(container.getMBeanKeyProperties()); int seq = 0; // Pipeline may not be present in unit testing Pipeline p = container.getPipeline(); if (p != null) { for (Valve valve : p.getValves()) { // Skip null valves if (valve == null) { continue; } // Only compare valves in pipeline until we find this valve if (valve == this) { break; } if (valve.getClass() == this.getClass()) { // Duplicate valve earlier in pipeline // increment sequence number seq ++; } } } if (seq > 0) { name.append(",seq="); name.append(seq); } String className = this.getClass().getName(); int period = className.lastIndexOf('.'); if (period >= 0) { className = className.substring(period + 1); } name.append(",name="); name.append(className); return name.toString(); } @Override public String getDomainInternal() { Container c = getContainer(); if (c == null) { return null; } else { return c.getDomain(); } } } Standardpipline实现

  里面的方法很简单,直接贴代码。它必须继承LifecycleBase,同时实现Pipline.

  你理解贴个图

public class StandardPipeline extends LifecycleBase implements Pipeline { private static final Log log = LogFactory.getLog(StandardPipeline.class); private static final StringManager sm = StringManager.getManager(Constants.Package); // ----------------------------------------------------------- Constructors /** * Construct a new StandardPipeline instance with no associated Container. */ public StandardPipeline() { this(null); } /** * Construct a new StandardPipeline instance that is associated with the * specified Container. * * @param container The container we should be associated with */ public StandardPipeline(Container container) { super(); setContainer(container); } // ----------------------------------------------------- Instance Variables /** * The basic Valve (if any) associated with this Pipeline. */ protected Valve basic = null; /** * The Container with which this Pipeline is associated. */ protected Container container = null; /** * The first valve associated with this Pipeline. */ protected Valve first = null; // --------------------------------------------------------- Public Methods @Override public boolean isAsyncSupported() { Valve valve = (first!=null)?=null)?first:basic; boolean supported = true; while (supported && valve!=null) { supported = supported & valve.isAsyncSupported(); valve = valve.getNext(); } return supported; } @Override public void findNonAsyncValves(Set result) { Valve valve = (first!=null) ? first : basic; while (valve != null) { if (!valve.isAsyncSupported()) { result.add(valve.getClass().getName()); } valve = valve.getNext(); } } // ------------------------------------------------------ Contained Methods /** * Return the Container with which this Pipeline is associated. */ @Override public Container getContainer() { return this.container; } /** * Set the Container with which this Pipeline is associated. * * @param container The new associated container */ @Override public void setContainer(Container container) { this.container = container; } @Override protected void initInternal() { // NOOP } /** * Start {@link Valve}s) in this pipeline and implement the requirements * of {@link 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 { // Start the Valves in our pipeline (including the basic), if any Valve current = first; if (current == null) { current = basic; } while (current != null) { if (current instanceof Lifecycle) ((Lifecycle) current).start(); current = current.getNext(); } setState(LifecycleState.STARTING); } /** * Stop {@link Valve}s) in this pipeline and implement the requirements * of {@link LifecycleBase#stopInternal()}. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ @Override protected synchronized void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); // Stop the Valves in our pipeline (including the basic), if any Valve current = first; if (current == null) { current = basic; } while (current != null) { if (current instanceof Lifecycle) ((Lifecycle) current).stop(); current = current.getNext(); } } @Override protected void destroyInternal() { Valve[] valves = getValves(); for (Valve valve : valves) { removeValve(valve); } } /** * Return a String representation of this component. */ @Override public String toString() { return ToStringUtil.toString(this); } // ------------------------------------------------------- Pipeline Methods /** *

Return the Valve instance that has been distinguished as the basic * Valve for this Pipeline (if any). */ @Override public Valve getBasic() { return this.basic; } /** *

Set the Valve instance that has been distinguished as the basic * Valve for this Pipeline (if any). Prior to setting the basic Valve, * the Valve's setContainer() will be called, if it * implements Contained, with the owning Container as an * argument. The method may throw an IllegalArgumentException * if this Valve chooses not to be associated with this Container, or * IllegalStateException if it is already associated with * a different Container.

* * @param valve Valve to be distinguished as the basic Valve */ @Override public void setBasic(Valve valve) { // Change components if necessary Valve oldBasic = this.basic; if (oldBasic == valve) return; // Stop the old component if necessary if (oldBasic != null) { if (getState().isAvailable() && (oldBasic instanceof Lifecycle)) { try { ((Lifecycle) oldBasic).stop(); } catch (LifecycleException e) { log.error(sm.getString("standardPipeline.basic.stop"), e); } } if (oldBasic instanceof Contained) { try { ((Contained) oldBasic).setContainer(null); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } // Start the new component if necessary if (valve == null) return; if (valve instanceof Contained) { ((Contained) valve).setContainer(this.container); } if (getState().isAvailable() && valve instanceof Lifecycle) { try { ((Lifecycle) valve).start(); } catch (LifecycleException e) { log.error(sm.getString("standardPipeline.basic.start"), e); return; } } // Update the pipeline Valve current = first; while (current != null) { if (current.getNext() == oldBasic) { current.setNext(valve); break; } current = current.getNext(); } this.basic = valve; } /** *

Add a new Valve to the end of the pipeline associated with this * Container. Prior to adding the Valve, the Valve's * setContainer() method will be called, if it implements * Contained, with the owning Container as an argument. * The method may throw an * IllegalArgumentException if this Valve chooses not to * be associated with this Container, or IllegalStateException * if it is already associated with a different Container.

* * @param valve Valve to be added * * @exception IllegalArgumentException if this Container refused to * accept the specified Valve * @exception IllegalArgumentException if the specified Valve refuses to be * associated with this Container * @exception IllegalStateException if the specified Valve is already * associated with a different Container */ @Override public void addValve(Valve valve) { // Validate that we can add this Valve if (valve instanceof Contained) ((Contained) valve).setContainer(this.container); // Start the new component if necessary if (getState().isAvailable()) { if (valve instanceof Lifecycle) { try { ((Lifecycle) valve).start(); } catch (LifecycleException e) { log.error(sm.getString("standardPipeline.valve.start"), e); } } } // Add this Valve to the set associated with this Pipeline if (first == null) { first = valve; valve.setNext(basic); } else { Valve current = first; while (current != null) { if (current.getNext() == basic) { current.setNext(valve); valve.setNext(basic); break; } current = current.getNext(); } } container.fireContainerEvent(Container.ADD_VALVE_EVENT, valve); } /** * Return the set of Valves in the pipeline associated with this * Container, including the basic Valve (if any). If there are no * such Valves, a zero-length array is returned. */ @Override public Valve[] getValves() { List valveList = new ArrayList<>(); Valve current = first; if (current == null) { current = basic; } while (current != null) { valveList.add(current); current = current.getNext(); } return valveList.toArray(new Valve[0]); } public ObjectName[] getValveObjectNames() { List valveList = new ArrayList<>(); Valve current = first; if (current == null) { current = basic; } while (current != null) { if (current instanceof JmxEnabled) { valveList.add(((JmxEnabled) current).getObjectName()); } current = current.getNext(); } return valveList.toArray(new ObjectName[0]); } /** * Remove the specified Valve from the pipeline associated with this * Container, if it is found; otherwise, do nothing. If the Valve is * found and removed, the Valve's setContainer(null) method * will be called if it implements Contained. * * @param valve Valve to be removed */ @Override public void removeValve(Valve valve) { Valve current; if(first == valve) { first = first.getNext(); current = null; } else { current = first; } while (current != null) { if (current.getNext() == valve) { current.setNext(valve.getNext()); break; } current = current.getNext(); } if (first == basic) first = null; if (valve instanceof Contained) ((Contained) valve).setContainer(null); if (valve instanceof Lifecycle) { // Stop this valve if necessary if (getState().isAvailable()) { try { ((Lifecycle) valve).stop(); } catch (LifecycleException e) { log.error(sm.getString("standardPipeline.valve.stop"), e); } } try { ((Lifecycle) valve).destroy(); } catch (LifecycleException e) { log.error(sm.getString("standardPipeline.valve.destroy"), e); } } container.fireContainerEvent(Container.REMOVE_VALVE_EVENT, valve); } @Override public Valve getFirst() { if (first != null) { return first; } return basic; } } 在ContainerBase中使用Pipline

 

  所以Pipline是如何在容器中使用的呢? Pipline是如何在容器中使用的?

  由于Container都涉及到,实现方法必须在抽象实现类中,因此必须在ContainerBase中实现。 初始化 /** * The Pipeline object with which this Container is associated. */ protected final Pipeline pipeline = new StandardPipeline(this); /** * Return the Pipeline object that manages the Valves associated with * this Container. */ @Override public Pipeline getPipeline() { return this.pipeline; } Lifecycle模板方法 @Override protected synchronized void startInternal() throws LifecycleException { ... // Start the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle) { ((Lifecycle) pipeline).start(); } ... } @Override protected synchronized void stopInternal() throws LifecycleException { ... // Stop the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle && ((Lifecycle) pipeline).getState().isAvailable()) { ((Lifecycle) pipeline).stop(); } ... } @Override protected void destroyInternal() throws LifecycleException { ... // Stop the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle) { ((Lifecycle) pipeline).destroy(); } ... super.destroyInternal(); } 重点是backgroundProcess方法 @Override public void backgroundProcess() { if (!getState().isAvailable()) return; Cluster cluster = getClusterInternal(); if (cluster != null) { try { cluster.backgroundProcess(); } catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.cluster", cluster), e); } } Realm realm = getRealmInternal(); if (realm != null) { try { realm.backgroundProcess(); } catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.realm", realm), e); } } // 看这里 Valve current = pipeline.getFirst(); while (current != null) { try { current.backgroundProcess(); } catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.valve", current), e); } current = current.getNext(); } fireLifecycleEvent(Lifecycle.PERIODIC_EVENT, null); }

  看看相关链路

比较下两种责任链模式 管道/阀门 过滤器链/过滤器 管道(Pipeline) 过滤器链(FilterChain) 阀门(Valve) 过滤器(Filter) 底层实现为有头(first)、尾(basic)指针单向链表 底层实现为数组 invokeevalve的核心方法(request,response) dofilter核心方法(request,response,chain) pipeline.getFirst().invoke(request,response) filterchain.doFilter(request,response)