Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the Tomcat architecture and startup process?

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains the "Tomcat architecture and startup process is how", the content of the explanation is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in-depth, together to study and learn "Tomcat architecture and startup process is how" it!

Tomcat-9.0.0.M22 is the latest version of Tomcat, but it has not been released yet. It implements Servlet4.0 and JSP2.3 and provides many new features. JDK support of 1.8 or above is required. For more information, please refer to Tomcat-9.0-doc.

Tomcat-9.0-doc https://tomcat.apache.org/tomcat-9.0-doc/index.html

Overview

Bootstrap, as the startup class of Tomcat to the outside world, in the $CATALINA_BASE/bin directory, it creates, initializes and starts an instance of Catalina through reflection.

Catalina parses the $CATALINA_BASE/conf/server.xml file and creates StandardServer, StandardService, StandardEngine, StandardHost, etc.

StandardServer represents the entire Servlet container, which contains one or more StandardService

StandardService contains one or more Connector, and an Engine,Connector and Engine are created when parsing conf/server.xml files. The standard implementation of Engine in Tomcat is StandardEngine.

MapperListener implements the LifecycleListener and ContainerListener interfaces to listen for container events and lifecycle events. The listener instance listens to all containers, including StandardEngine, StandardHost, StandardContext, and StandardWrapper, and registers the container to Mapper when the container changes.

Mapper maintains the mapping of URL to containers. When the request arrives, it is decided which Host, Context, Wrapper to map the request to based on the mapping information in Mapper.

Http11NioProtocol is used to process requests from HTTP/1.1

NioEndpoint is the endpoint of the connection, and this class is the core class in the request processing process, which will be highlighted.

CoyoteAdapter is used to pass the request from Connctor to Container for processing. Decouple Connctor from Container.

StandardEngine represents the Servlet engine, which is used to process Request accepted by Connector. Contains one or more Host (virtual hosts), and the standard implementation of Host is StandardHost.

StandardHost represents a virtual host and is used to deploy applications on that virtual host. It usually contains multiple Context (Context represents the application in Tomcat). The standard implementation of Context in Tomcat is StandardContext.

StandardContext represents a stand-alone application, which usually contains multiple Wrapper, and a Wrapper container encapsulates a Servlet,Wrapper. The standard implementation is StandardWrapper.

The StandardPipeline component represents a pipeline in conjunction with the Valve (valve) to process the request. StandardPipeline contains multiple Valve, and when a request needs to be processed, the invoke method of Valve is called one by one to process Request and Response. In particular, there is a special Valve called basicValve, each standard container has a specified BasicValve, they do the core work.

StandardEngine is StandardEngineValve, which is used to map Request to the specified Host

StandardHost is StandardHostValve, which is used to map Request to the specified Context

StandardContext is StandardContextValve, which is used to map Request to a specified Wrapper

StandardWrapper is StandardWrapperValve, which is used to load the Servlet specified by Rquest and to call the Service method of Servlet.

Tomcat init

When you start Bootstrap through a. / startup.sh script or directly through the java command, the Tomcat startup process officially begins, and the entry point is the main method of the Bootstrap class.

The startup process is divided into two steps, namely init and start. This section mainly introduces init.

Initialize the class loader. [about Tomcat class loading mechanism, you can refer to an article I wrote earlier: talking about Java class loading mechanism]

The scanning repository of the class loader is obtained by obtaining common.loader and other properties from the CatalinaProperties class. The CatalinaProperties class calls the loadProperties () method in the static block of, loading attributes from the conf/catalina.properties file. (that is, the properties are loaded when the class is created).

Create an instance of URLClassLoader through ClassLoaderFactory

Create an instance of Catalina through reflection and set parentClassLoader

SetAwait (true). Set the await property of Catalina to true. At the end of the Start phase, if the attribute is true,Tomcat, it listens for SHUTDOWN commands in the main thread. The default port is 8005. When the command is received, execute the stop () method of Catalina to shut down the Tomcat server.

CreateStartDigester (). This method of Catalina is used to create an instance of Digester and add a RuleSet that parses the conf/server.xml. Digester was originally an open source project of Apache specializing in parsing XML files, but I think Tomcat-9.0.0.M22 integrates these classes directly into Tomcat instead of introducing jar files. The principle of Digester tools is beyond the scope of this article. If you are interested, you can refer to the chapter The Digester Component-Apache or "How Tomcat works"-Digester [recommendation].

The parse () method is the process by which Digester handles conf/server.xml 's creation of individual components. Value is that these components are created using reflection. In particular, when creating Digester, we added some special rule Set to create some very core components, which are not available in conf/server.xml but are of great use. Here is a brief introduction, which is described in more detail when you use Start:

EngineConfig . The implementation class of LifecycleListener, which is called after triggering the life cycle event of Engine. This listener is not very useful, just to print the log.

HostConfig . The implementation class of LifecycleListener, which is called after triggering the life cycle event of Host. The purpose of this listener is to deploy the application, which includes conf/

All Context xml files in the / / directory and applications in the webapps directory, whether they are war files or unzipped directories. In addition, the hot deployment of the application by the background process is also the responsibility of the listener.

ContextConfig . The implementation class of LifecycleListener, which is called when the life cycle event of the Context is triggered. The role of this listener is to configure the application. It reads and merges the web.xml of conf/web.xml and the application, analyzes the annotations of the Class files in / WEB-INF/classes/ and / WEB-INF/lib/*.jar, and configures all Servlet, ServletMapping, Filter, FilterMapping, and Listener into StandardContext for later use. Of course, there are some other application parameters in web.xml that will eventually be configured in StandardContext.

ReconfigureStartStopExecutor () is used to reconfigure the Executor that starts and stops the child container. The default is 1 thread. We can configure the startStopThreads of Engine in conf/server.xml to specify the number of threads used to start and stop the child container. If we configure 0, we will use Runtime.getRuntime (). AvailableProcessors () as the number of threads, if configured as a negative number, we will use Runtime.getRuntime (). AvailableProcessors () + configuration value, and small and 1, use 1 as the number of threads. When the number of threads is 1, use InlineExecutorService, which directly uses the current thread to perform the start-stop operation, otherwise use ThreadPoolExecutor to execute, and the maximum number of threads is the value we configured.

It is important to note that the init operation of Host is done during the Start phase, and after StardardHost is created, the default value of its state property is LifecycleState.NEW, so it is initialized before it calls startInternal ().

Tomcat Start [Deployment]

In the figure, it is skipped directly from the real execution process of StandardHost Start StandardContext, because there is no Context configured in the conf/server.xml file, so an empty array is returned when findChildren () looks for the child container, so the for loop of the sub-container is skipped directly after traversing the sub-container.

Triggers the BEFORE_START_EVENT lifecycle event of Host, and HostConfig calls its beforeStart () method to create $CATALINA_BASE/webapps& $CATALINA_BASE/conf/

/ / directory.

Triggering the START_EVENT lifecycle event of Host, HostConfig calls its start () method to start deployment in $CATALINA_BASE/webapps & $CATALINA_BASE/conf/

/ / applications under the directory.

Parsing $CATALINA_BASE/conf/

All the XML files that define Context in the / / directory, and add them to StandardHost. These XML files are called application descriptors. Because of this, we can configure a virtual path to save the pictures used in the application. For detailed configuration process, please refer to the Development Environment configuration Guide-6.3. Configure the picture storage directory

Deploy all the WAR files under $CATALINA_BASE/webapps and add them to StandardHost.

Deploy all the extracted directories under $CATALINA_BASE/webapps and add them to StandardHost.

In particular, when added to StandardHost, the start () method of StandardContext is called directly to start the application. For the steps to start the application, see the Context Start section.

Both StandardEngine and StandardContext call their respective threadStart () methods when they start, which creates a new background thread to handle background events for the container and its subcontainers and components within the container. StandardEngine creates a background thread directly. StandardContext is not created by default and shares the same as StandardEngine. The background threading mechanism is to periodically call the component's backgroundProcess () method. Please see the Background process section for details.

MapperListener

The addListeners (engine) method adds the listener to StandardEngine and all of its child containers

RegisterHost () registers all Host and their child containers with Mapper for later request processing.

When a new application (StandardContext) is added, the container event of the Host is triggered, and the mapping of the new application is registered with the Mapper through the MapperListener.

After all the Start work is done, Catalina creates a CatalinaShutdownHook and registers with JVM. CatalinaShutdownHook inherits Thread and is the inner class of Catalina. The stop () method of Catalina is called directly in its run method to shut down the entire server. The reason for registering the Thread to JVM is to prevent the user from terminating the Tomcat abnormally, such as directly closing the command window. When you close the command window directly, the operating system sends a termination signal to JVM, and then JVM starts the registered ShutdownHook one by one before exiting to close the corresponding resources.

Context Start

The StandRoot class implements the WebResourceRoot interface, which holds all the resources of an application, generally speaking, all resources deployed to the corresponding Context directory under the webapps directory. Because I am not very interested in the resource management part of Tomcat for the time being, I only have a simple understanding of the resource management related classes and do not delve into the source code.

The resourceStart () method initially configures the StandardRoot

PostWorkDirectory () is used to create the corresponding working directory $CATALINA_BASE/work/

/, this directory is used to store temporary files.

StardardContext is just a container, while ApplicationContext is a real running environment for an application. Related classes and operations will be supplemented after reading the request processing process.

StardardContext triggers CONFIGURE_START_EVENT lifecycle events, and ContextConfig starts calling configureStart () to configure the application.

This process parses and merges conf/web.xml & conf/

/ / web.xml.default & configuration in webapps//WEB-INF/web.xml.

Configure the parameters in the configuration file to StandardContext, which mainly include Servlet, Filter, and Listener.

Since annotations are directly supported from Servlet3.0, the server must be able to handle annotated classes. Tomcat registers the scanned Servlet, Filter and Listerner to StandardContext by analyzing the Class file in WEB-INF/classes/ and the jar package under WEB-INF/lib/.

SetConfigured (true), which is a very critical operation, identifies the successful configuration of Context. If this value is not set to true, Context will fail to start.

Background process

The role of the background process is to deal with periodic events in the Servlet engine, and the processing cycle is 10s by default.

In particular, the backgroundProcess () method of StandardHost triggers the PERIODIC_EVENT lifecycle event of Host. HostConfig then invokes its check () method to reload loaded and redeployed applications or hot deploy newly deployed applications. Hot deployment is consistent with the deployment steps described earlier, and the reload () process simply calls setPause (true), stop (), start (), and setPause (false) sequentially, where the role of setPause (true) is to temporarily stop accepting requests.

How to read excellent open source projects

The real first time to read the open source project source code, the harvest is still very great. I have made progress in architecture design, object-oriented thinking, design patterns, Clean Code, and so on. Reading excellent open source projects is actually a very cool thing, because from time to time you will find a new design idea, and then can't help but sigh that it can still be like this! Of course, there will be some pain points when reading, for example, encounter a variable, but life or death is can not find the initialization location, sometimes through the Find Usage tool can be found, but some can not find only from the beginning to one side of the source code. Sometimes I come across a design idea that I don't understand why it is designed and so on, and this situation can only be solved by analyzing a higher-level architecture and so on.

Let me briefly share how I read the source code of open source projects.

First find some books about the project architecture, the project architecture is the core of the project, read the architecture to read the high-level design ideas, read the source code to read the low-level implementation details. With the guidance of high-level design ideas, the source code will be easy to read, because when you read it, you know very well where the source code you are reading now is in the whole project architecture. I first passed the book "How Tomcat works" before reading the Tomcat source code, and then read the second chapter of "Tomcat Architecture parsing" to get a preliminary understanding of the architecture of Tomcat. (PS: "How Tomcat works" is all in English, but it reads very smoothly. Although it is based on Tomcat 4 and 5, the architecture of Tomcat has not changed much. The new version of Tomcat just adds some components. If you want to learn Tomcat, this book is the first one!

If you can't find a book on architecture, draw your own class diagrams. Generally speaking, open source projects are to provide services, we take the process of providing services as the main line to analyze the source code, so that the purpose will be stronger, the classes involved in the process will be drawn into the class diagram, and the final class diagram is the architecture! However, you have to find the entry point of the process before the analysis, otherwise there is no way to start the analysis. Take Tomcat as an example, his mainline process can be roughly divided into three: startup, deployment, and request processing. Their entry points are the Bootstrap class and the Acceptor class that accepts requests!

With reading ideas, let's talk about tools. The reading tool I use is IntelliJ IDEA, a very powerful IDE, which may be heavyweight. If you have other lighter Linux platform source code reading tools, you can recommend them to me.

The Structure column can customize the list of fields and methods in the class, and then group the fields and methods according to the inheritance structure, so you can directly see which class the fields and methods are defined in the inheritance structure. When you click on the method and domain, you can also automatically scroll to the source code and so on.

Right-click-> Diagrams-> show Diagram in the source code to show the inheritance structure of the class, which contains all the ancestors and interfaces of the class. Select the specified parent class and interface in the figure, right-click-> show Implementations, and IDEA will list the implementation class of the interface or its subclasses.

FindUsage, Go To Declaration and so on will not say any more.

Thank you for your reading, the above is the content of "Tomcat architecture and startup process". After the study of this article, I believe you have a deeper understanding of the Tomcat architecture and startup process, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report