Tomcat 监听初始化流程

开篇

 这篇博文的主要目的是为了理清楚Tomcat监听的初始化流程,所谓的监听初始化流程是指Tomcat启动后直至Accept过程就绪能够监听连接到来为止。

 只有理清楚监听的初始化后流程后才能更好的理解Tomcat处理请求的过程,所以也算是基础的一部分吧。

 整篇博文的思路脉络是先讲解初始化过程中各个组件的关联(架构图+源码),然后讲解清楚初始化的过程(时序图+源码),我想应该是可以讲明白的。

文末惯例有招聘信息彩蛋。


组件关联说明

组件关联

说明:

    1. Service组件(StandardService)包含Connector组件。
    1. Connector组件包含ProtocolHandler组件。
    1. ProtocolHandler组件包含AbstractEndpoint组件。
    1. Connector包含CoyoteAdapter对象,CoyoteAdapter保存至ProtocolHandler对象。


StandardService

public class StandardService extends LifecycleMBeanBase implements Service {
    protected Connector connectors[] = new Connector[0];
}

说明:

    1. StandardService包含Connector对象。

Connector

public class Connector extends LifecycleMBeanBase  {

   protected Service service = null;
    protected int port = -1;
    // 默认的protocolHandler的实现类
    protected String protocolHandlerClassName =
        "org.apache.coyote.http11.Http11NioProtocol";
    // protocolHandler对象
    protected final ProtocolHandler protocolHandler;
    // CoyoteAdapter对象
    protected Adapter adapter = null;

说明:

  1. Connector对象包含ProtocolHandler对象。


ProtocolHandler

ProtocolHandler类关系图

说明:

  1. ProtocolHandler具体实现包括ajp和http两类。

public abstract class AbstractProtocol<S> implements ProtocolHandler,
        MBeanRegistration {

    private final AbstractEndpoint<S> endpoint;
    private Handler<S> handler;
}

说明:

  1. ProtocolHandler的抽象实现类AbstractProtocol包含EndPoint对象。


public class Http11NioProtocol extends AbstractHttp11JsseProtocol<NioChannel> {

    public Http11NioProtocol() {
        super(new NioEndpoint());
    }
}

说明:

  1. Http11NioProtocol作为ProtocolHandler的实现类之一,注意EndPoint的对象的创建。


Endpoint


说明:

    1. AbstractEndpoint的实现类包括NioEndpoint、Nio2Endpoint、AprEndpoint。


public abstract class AbstractEndpoint<S> {
    protected Acceptor[] acceptors;
    private int port;
    private InetAddress address;
}

说明:

    1. AbstractEndpoint包含 Acceptor[] acceptors。
    1. AbstractEndpoint包含监听port和address。


监听初始化流程

监听初始化流程

说明:

    1. 监听的初始化过程包括三个阶段,体现在Connector创建&初始化&启动。
    1. Connector创建包括创建Connector、protocolHandler、Endpoint核心对象。
    1. Connector的初始化包括初始化Connector、protocolHandler、Endpoint核心对象。
    1. Connector的启动包括启动Connector、protocolHandler、Endpoint核心对象。
    1. TCP当中经典server端启动过程在Endpoint对象中实现,负责处理连接请求。


Connector

public class Connector extends LifecycleMBeanBase  {
    public Connector(String protocol) {
        setProtocol(protocol);
        ProtocolHandler p = null;
        try {
            Class<?> clazz = Class.forName(protocolHandlerClassName);
            p = (ProtocolHandler) clazz.getConstructor().newInstance();
        } catch (Exception e) {
        } finally {
            this.protocolHandler = p;
        }
    }



    protected void initInternal() throws LifecycleException {
        super.initInternal();
        adapter = new CoyoteAdapter(this);
        protocolHandler.setAdapter(adapter);

        try {
            protocolHandler.init();
        } catch (Exception e) {
          
        }
    }


    protected void startInternal() throws LifecycleException {
        setState(LifecycleState.STARTING);
        try {
            protocolHandler.start();
        } catch (Exception e) {
          
        }
    }
}

说明:

    1. Connector包含创建、初始化、启动三个阶段。
    1. Connector的三个阶段对应protocolHnalder的创建、初始化、启动三个阶段。


protocolHandler

public abstract class AbstractProtocol<S> implements ProtocolHandler,
        MBeanRegistration {

    private final AbstractEndpoint<S> endpoint;
    private Handler<S> handler;

    public AbstractProtocol(AbstractEndpoint<S> endpoint) {
        this.endpoint = endpoint;
        setSoLinger(Constants.DEFAULT_CONNECTION_LINGER);
        setTcpNoDelay(Constants.DEFAULT_TCP_NO_DELAY);
    }


    public void init() throws Exception {
        if (getLog().isInfoEnabled()) {
            getLog().info(sm.getString("abstractProtocolHandler.init", getName()));
        }

        if (oname == null) {
            // Component not pre-registered so register it
            oname = createObjectName();
            if (oname != null) {
                Registry.getRegistry(null, null).registerComponent(this, oname, null);
            }
        }

        if (this.domain != null) {
            rgOname = new ObjectName(domain + ":type=GlobalRequestProcessor,name=" + getName());
            Registry.getRegistry(null, null).registerComponent(
                    getHandler().getGlobal(), rgOname, null);
        }

        String endpointName = getName();
        endpoint.setName(endpointName.substring(1, endpointName.length()-1));
        endpoint.setDomain(domain);

        endpoint.init();
    }


    public void start() throws Exception {
        endpoint.start();
        asyncTimeout = new AsyncTimeout();
        Thread timeoutThread = new Thread(asyncTimeout, getNameInternal() + "-AsyncTimeout");
        int priority = endpoint.getThreadPriority();
        if (priority < Thread.MIN_PRIORITY || priority > Thread.MAX_PRIORITY) {
            priority = Thread.NORM_PRIORITY;
        }
        timeoutThread.setPriority(priority);
        timeoutThread.setDaemon(true);
        timeoutThread.start();
    }
}


public class Http11NioProtocol extends AbstractHttp11JsseProtocol<NioChannel> {

    public Http11NioProtocol() {
        super(new NioEndpoint());
    }
}

说明:

    1. ProtocolHandler包含创建、初始化、启动三个阶段。
    1. ProtocolHandler的三个阶段对应Endpoint的创建、初始化、启动三个阶段。


Endpoint

public abstract class AbstractEndpoint<S> {

    public void init() throws Exception {
        if (bindOnInit) {
            bind();
            bindState = BindState.BOUND_ON_INIT;
        }
        if (this.domain != null) {
            // Register endpoint (as ThreadPool - historical name)
            oname = new ObjectName(domain + ":type=ThreadPool,name=\"" + getName() + "\"");
            Registry.getRegistry(null, null).registerComponent(this, oname, null);

            for (SSLHostConfig sslHostConfig : findSslHostConfigs()) {
                registerJmx(sslHostConfig);
            }
        }
    }

    public final void start() throws Exception {
        if (bindState == BindState.UNBOUND) {
            bind();
            bindState = BindState.BOUND_ON_START;
        }
        startInternal();
    }

    public abstract void startInternal() throws Exception;

    public abstract void bind() throws Exception;
}

说明:

    1. Endpoint包含创建、初始化、启动三个阶段。
    1. AbstractEndpoint类板设计模式提供init&start方法。
    1. AbstractEndpoint类init方法实现bind操作,start方法负责启动监听。


public class NioEndpoint extends AbstractJsseEndpoint<NioChannel> {

    public void bind() throws Exception {

        if (!getUseInheritedChannel()) {
            serverSock = ServerSocketChannel.open();
            socketProperties.setProperties(serverSock.socket());
            InetSocketAddress addr = (getAddress()!=null?new InetSocketAddress(getAddress(),getPort()):new InetSocketAddress(getPort()));
            serverSock.socket().bind(addr,getAcceptCount());
        } else {
            // Retrieve the channel provided by the OS
            Channel ic = System.inheritedChannel();
            if (ic instanceof ServerSocketChannel) {
                serverSock = (ServerSocketChannel) ic;
            }
            if (serverSock == null) {
                throw new IllegalArgumentException(sm.getString("endpoint.init.bind.inherited"));
            }
        }
        serverSock.configureBlocking(true); //mimic APR behavior

        // Initialize thread count defaults for acceptor, poller
        if (acceptorThreadCount == 0) {
            // FIXME: Doesn't seem to work that well with multiple accept threads
            acceptorThreadCount = 1;
        }
        if (pollerThreadCount <= 0) {
            //minimum one poller thread
            pollerThreadCount = 1;
        }
        setStopLatch(new CountDownLatch(pollerThreadCount));

        // Initialize SSL if needed
        initialiseSsl();

        selectorPool.open();
    }

    public void startInternal() throws Exception {

        if (!running) {
            running = true;
            paused = false;

            processorCache = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,
                    socketProperties.getProcessorCache());
            eventCache = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,
                            socketProperties.getEventCache());
            nioChannels = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,
                    socketProperties.getBufferPool());

            // Create worker collection
            if ( getExecutor() == null ) {
                createExecutor();
            }

            initializeConnectionLatch();

            // Start poller threads
            pollers = new Poller[getPollerThreadCount()];
            for (int i=0; i<pollers.length; i++) {
                pollers[i] = new Poller();
                Thread pollerThread = new Thread(pollers[i], getName() + "-ClientPoller-"+i);
                pollerThread.setPriority(threadPriority);
                pollerThread.setDaemon(true);
                pollerThread.start();
            }

            startAcceptorThreads();
        }
    }


    protected class Acceptor extends AbstractEndpoint.Acceptor {
        public void run() {

            int errorDelay = 0;

            while (running) {
                while (paused && running) {
                    state = AcceptorState.PAUSED;
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        // Ignore
                    }
                }

                if (!running) {
                    break;
                }
                state = AcceptorState.RUNNING;

                try {
                    countUpOrAwaitConnection();
                    SocketChannel socket = null;
                    try {
                        socket = serverSock.accept();
                    } catch (IOException ioe) {

                    }
                    errorDelay = 0;

                    if (running && !paused) {
                        if (!setSocketOptions(socket)) {
                            closeSocket(socket);
                        }
                    } else {
                        closeSocket(socket);
                    }
                } catch (Throwable t) {
                }
            }
            state = AcceptorState.ENDED;
        }
    }


    protected boolean setSocketOptions(SocketChannel socket) {
        try {
            socket.configureBlocking(false);
            Socket sock = socket.socket();
            socketProperties.setProperties(sock);

            NioChannel channel = nioChannels.pop();
            if (channel == null) {
                SocketBufferHandler bufhandler = new SocketBufferHandler(
                        socketProperties.getAppReadBufSize(),
                        socketProperties.getAppWriteBufSize(),
                        socketProperties.getDirectBuffer());
                if (isSSLEnabled()) {
                    channel = new SecureNioChannel(socket, bufhandler, selectorPool, this);
                } else {
                    channel = new NioChannel(socket, bufhandler);
                }
            } else {
                channel.setIOChannel(socket);
                channel.reset();
            }
            getPoller0().register(channel);
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            try {
                log.error("",t);
            } catch (Throwable tt) {
                ExceptionUtils.handleThrowable(tt);
            }
            // Tell to close the socket
            return false;
        }
        return true;
    }

}

说明:

    1. NioEndpoint是AbstractEndpoint的具体实现类之一。
    1. NioEndpoint实现具体的bind和start方法。
    1. NioEndpoint的Acceptor作为具体的实现负责监听连接。
    1. setSocketOptions负责处理新连接并通过getPoller0().register(channel)注册。


参考文章

谈谈 Tomcat 请求处理流程
Tomcat 请求处理流程详解

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,646评论 4 366
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,979评论 1 301
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,391评论 0 250
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,356评论 0 215
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,740评论 3 293
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,836评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,022评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,764评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,487评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,728评论 2 252
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,200评论 1 263
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,548评论 3 260
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,217评论 3 241
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,134评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,921评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,919评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,766评论 2 274