Tomcat parsing (quad)-handling HTTP request process

Source: Internet
Author: User

Disclaimer: The source version is Tomcat 6.0.35

The process of Tomcat initialization is described in the previous article, and this article describes the overall flow of Tomcat's handling of HTTP requests, in more detail.

In the previous article, the internal class acceptor in Jioendpoint was used to accept the socket request and call the Processsocket method for processing the request, so we'll start with this approach.

?
123456789101112 protectedbooleanprocessSocket(Socket socket) {        try{            if (executor == null) {                getWorkerThread().assign(socket);            else{                executor.execute(new SocketProcessor(socket));            }        catch(Throwable t) {            //……此处略去若干代码        }        return true;    }

In the above code, The first is to determine whether the process pool is configured in Server.xml, if configured, will use the thread pool for the requested processing, if not configured, will use the jioendpoint in its own implementation of the thread pool workerstack to do the request processing, we will introduce Workerstack request Processing mode.

?
1234567891011121314 protectedWorker getWorkerThread() {        // Allocate a new worker thread        synchronized (workers) {            Worker workerThread;            while((workerThread = createWorkerThread()) == null) {                try{                    workers.wait();                catch(InterruptedException e) {                    // Ignore                }            }            returnworkerThread;        }    }

In the above code, we finally return an instance of the worker, which has the processing of the request, and here we look at the Createworkerthread method, which generates or takes a thread in the threads pool.

?
123456789101112131415161718192021 protected Worker createWorkerThread() {        synchronized(workers) {            if(workers.size() > 0) {            //如果线程池中有空闲的线程,取一个                curThreadsBusy++;                returnworkers.pop();            }            if((maxThreads > 0) && (curThreads < maxThreads)) {                //如果还没有超过最大线程数,会新建一个线程                curThreadsBusy++;                return(newWorkerThread());            else{                if(maxThreads < 0) {                    curThreadsBusy++;                    return (newWorkerThread());                else{                    return(null);                }            }        }    }

In this way, the thread has been acquired, and then, most crucially, the calling thread implements the worker's Run method:

?
1234567891011121314151617 publicvoidrun() {            // Process requests until we receive a shutdown signal            while(running) {                // Wait for the next socket to be assigned                Socket socket = await();                if(socket == null)                    continue;                   if(!setSocketOptions(socket) || !handler.process(socket)) {                    try{                        socket.close();                    catch(IOException e) {                    }                }                socket = null;                recycleWorkerThread(this);            }        }

This is closely related to the request processing is handler.process (socket) This code, here handle corresponding class is http11protocol in the inner class Http11connectionhandler, in subsequent processing, There will be some preprocessing of the request, we use a time series diagram to represent:

In this process, the original socket will be processed, to Coyoteadapter, The accepted parameters are already org.apache.coyote.Request and org.apache.coyote.Response, but it is important to note that these two classes are not our usual httpservletrequest and httpservletrespons The implementation class of E, but the data structure inside Tomcat, stores the information related to input and output. It is worth noting that in the service method of Coyoteadapter, a method named Postparserequest is called, in which the request is parsed and the map method of Mapper is called to determine which engine, Host and context to handle.

After the above information is processed, in the service method of Coyoteadapter, such a method is called:

?
1 connector.getContainer().getPipeline().getFirst().invoke(request, response);

This approach involves an important component of the container implementation class in the Tomcat component, where each container class component has a pipeline property that controls the processing of the request and, on pipeline, can add valve to control the process of the request. You can use the following diagram to indicate how the request is flowing:

The request can be imagined as the flow of water, the request needs to flow between the components, through a number of pipes and water valves, and so on all the valves are finished, the request is processed, and each component will have a default valve (standard as the class prefix) for the processing of requests, if the business needs, You can customize valve to install it in a container.

The subsequent processing is similar and will be processed in the order of the engine, Host, and context as resolved. Here are two time series diagrams that are not standard to describe this process:

In the above process, the Invoke method of valve of each container component is called Layer by level, where standardwrappervalve this standard valve will call Standardwrapper's allocate method to get the servlet that is really going to execute (all requests in Tomcat will eventually be mapped to a servlet, The same is true for static resources and JSPs), and to build the filter chain according to the requested address, execute each filter sequentially, and ultimately invoke the service method of the target servlet to complete the business's real processing.

The above process, involves a lot of important code, the subsequent articles will be an elective to analyze, such as:

    • Internalmapwrapper method in mapper (used to match the corresponding servlet)

    • Applicationfilterfactory Createfilterchain Method (the filter chain used to create the request)

    • Applicationfilterchain Internaldofilter method (used to execute the filter method and the last servlet)

    • Process methods in Http11processor, Preparerequest methods, and Prepareresponse methods (protocols, parameters, etc. that are used to handle HTTP requests)

At this point, we have a simple understanding of the processing flow of a request.

Tomcat parsing (quad)-handling HTTP request process

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.