【Tomcat9源码分析】Container、Pipeline和Vavle设计

转载请注明出处:http://blog.csdn.net/linxdcn/article/details/73800100


1 概述

如果你对Tomcat的整个框架、组件、请求流程不熟悉,建议你先阅读以下3篇Tomcat概述性的文章,再来看本篇文章:

【Tomcat9源码分析】组件与框架概述
【Tomcat9源码分析】生命周期、启动、停止概述
【Tomcat9源码分析】请求过程概述

Container是Tomcat中很重要的容器,主要包含Engine、Host、Context和Wrapper,其采用了责任链的设计模式,来处理一次请求。


2 Container分析

Container是一个接口,Tomcat提供了ContainerBase作为其实现的基类。

2.1 字段

public abstract class ContainerBase implements Container {

    // 子容器
    protected final HashMap<String, Container> children = new HashMap<>();

    // 监听事件
    protected final List<ContainerListener> listeners = new CopyOnWriteArrayList<>();

    // Container对应的Pipeline
    protected final Pipeline pipeline = new StandardPipeline(this);

    // 领域对象
    private volatile Realm realm = null;
}

2.2 启动

public abstract class ContainerBase implements Container {

    @Override
    protected synchronized void startInternal() throws LifecycleException {

        // 1 启动领域对象
        Realm realm = getRealmInternal();
        if (realm instanceof Lifecycle) {
            ((Lifecycle) realm).start();
        }

        // 2 启动子容器
        Container children[] = findChildren();
        List<Future<Void>> results = new ArrayList<>();
        for (int i = 0; i < children.length; i++) {
            results.add(startStopExecutor.submit(new StartChild(children[i])));
        }

        // 3 启动Pipeline
        if (pipeline instanceof Lifecycle)
            ((Lifecycle) pipeline).start();

        // 4 设置状态,启动本线程
        setState(LifecycleState.STARTING);
        threadStart();
    }
}
  1. 启动领域对象
  2. 启动子容器
  3. 启动Pipeline
  4. 设置状态,启动本线程

3 Pipeline分析

Pipeline是一个接口,其实现类是StandardPipeline

public class StandardPipeline extends LifecycleBase implements Pipeline {

    // 基础阀门
    protected Valve basic = null;

    // 关联的容器
    protected Container container = null;

    // 第一个阀门
    protected Valve first = null;

    @Override
    protected synchronized void startInternal() throws LifecycleException {

        Valve current = first;
        if (current == null) {
            current = basic;
        }

        // 依次启动所有Value,Value是一个链表结构
        while (current != null) {
            if (current instanceof Lifecycle)
                ((Lifecycle) current).start();
            current = current.getNext();
        }

        setState(LifecycleState.STARTING);
    }
}

4 Valve分析

Valve是一个接口,其基本实现的BaseValve类。

public abstract class ValveBase extends LifecycleMBeanBase implements Contained, Valve {

    // 关联的Container
    protected Container container = null;

    // 下一个Valve
    protected Valve next = null;

    @Override
    public Container getContainer() {
        return container;
    }

    // 初始化
    @Override
    protected void initInternal() throws LifecycleException {
        super.initInternal();
        containerLog = getContainer().getLogger();
    }

    // 启动
    @Override
    protected synchronized void startInternal() throws LifecycleException {
        setState(LifecycleState.STARTING);
    }
}

5 几个重要的Valve

5.1 StandardEngineValve

final class StandardEngineValve extends ValveBase {

    public final void invoke(Request request, Response response)
        throws IOException, ServletException {

        // 1 由request获取host
        Host host = request.getHost();
        if (host == null) {
            // ...省略
            return;
        }

        // 2 调用host的pipeline的vavle
        host.getPipeline().getFirst().invoke(request, response);
    }
}
  1. 根据request定位到可以处理的host对象
  2. 依次调用host里的pipeline上的valve

5.2 StandardEngineValve

final class StandardHostValve extends ValveBase {

    public final void invoke(Request request, Response response)
        throws IOException, ServletException {

        // 1 由request获取context
        Context context = request.getContext();

        try {

            // 2 调用context里的pipeline上的valve
            context.getPipeline().getFirst().invoke(request, response);

            // response已经返回
            response.setSuspended(false);
            Throwable t = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);

            // 3 如果有错误,重定向到错误页
            if (response.isErrorReportRequired()) {
                if (t != null) {
                    throwable(request, response, t);
                } else {
                    status(request, response);
                }
            }
        } 
    }
}
  1. 由request获取context
  2. 调用context里的pipeline上的valve
  3. 如果有错误,重定向到错误页

5.3 StandardContextValve

final class StandardContextValve extends ValveBase {
    @Override
    public final void invoke(Request request, Response response)
        throws IOException, ServletException {

        // 由request获取wrapper
        Wrapper wrapper = request.getWrapper();

        // ...省略

        // 调用wrapper里的pipeline上的valve
        wrapper.getPipeline().getFirst().invoke(request, response);
    }
}
  1. 由request获取wrapper
  2. 调用wrapper里的pipeline上的valve

5.4 StandardWrapperValve

final class StandardWrapperValve extends ValveBase {

    public final void invoke(Request request, Response response)
        throws IOException, ServletException {

        // 1 获取wrapper, context
        StandardWrapper wrapper = (StandardWrapper) getContainer();
        Servlet servlet = null;
        Context context = (Context) wrapper.getParent();

        // 2 加载servlet
        try {
            if (!unavailable) {
                servlet = wrapper.allocate();
            }
        } // ...省略catch

        // 3 新建一个 filter 链表
        ApplicationFilterChain filterChain =
                ApplicationFilterFactory.createFilterChain(request, wrapper, servlet);

        // servlet会放在 filter 链表最后,并且最后会调用servlet的service方法
        try {
            if ((servlet != null) && (filterChain != null)) {
                // Swallow output if needed
                if (context.getSwallowOutput()) {
                    // 4 调用 filter 链表上的 doFilter
                    filterChain.doFilter(request.getRequest(),
                            response.getResponse());
                }
            } 
        } // ...省略catch
    }
}
  1. 获取wrapper, context
  2. 加载servlet
  3. 新建一个 filter 链表,servlet会放在 filter 链表最后,并且最后会调用servlet的service方法
  4. 调用 filter 链表上的 doFilter

5 总结




转载请注明出处:http://blog.csdn.net/linxdcn/article/details/73800100

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页