1. Introduction

The browser enters the URL to the server to receive the data: juejin.cn/post/684490…

  • After the above steps, the data arrives at the server
  • The server restores the packet to the request parameters based on TCP
  • Notifies the specified Tomcat
  • Tomcat is both internal and external. Previously, ordinary Spring required additional configuration of Tomcat. Springboot simplifies the configuration and has Tomcat built in. You only need to configure the path and port number.
  • There are some differences between the startup of built-in and external Tomcat;

2. Important steps

  1. The client sends a request, and the server receives the request.
  2. The server restores the packet to request parameters according to TCP protocol.
  3. The server forwards the request to the corresponding Tomcat Server;
  4. Tomcat receives the request, finds the corresponding port, and performs host matching.
  5. Return the required object after the business logic processing, encapsulating HttpResponse;

Tomcat 2.1 response

Assume a request from the client as: http://localhost:8080/wsota/wsota_index.jsp

The main steps are as follows:

  1. The request is sent to native port 8080, picked up by the Coyote HTTP/1.1 Connector listening there
  2. The Connector passes the request to the Engine of its Service for processing and waits for a response from the Engine
  3. Engine gets the request localhost/wsota/wsota_index.jsp and matches all the virtual Host hosts it owns
  4. Engine matches a Host named localhost (if not, pass the request to that Host because it is defined as the Engine’s default Host)
  5. Localhost Host gets the request /wsota/wsota_index.jsp and matches all the contexts it owns
  6. Host matches the Context whose path is /wsota (if not, pass the request to the Context whose path is “”)
  7. The path=”/wsota” Context gets the request /wsota_index.jsp and looks for the corresponding servlet in its mapping table
  8. Context matches a servlet whose URL PATTERN is *.jsp, corresponding to the JspServlet class
  9. Construct the HttpServletRequest object and the HttpServletResponse object as parameters to call the doGet or doPost methods of the JspServlet
  10. Context returns the HttpServletResponse object to Host after execution
  11. Host returns the HttpServletResponse object to the Engine
  12. The Engine returns the HttpServletResponse object to the Connector
  13. The Connector returns the HttpServletResponse object to the client browser

Extension: Tomcat configuration file:

  • Context. XML: The Tomcat server periodically scans this file; Once it is discovered that the file has been modified (the timestamp has changed), the file is automatically reloaded without the need to restart the server.
<Context path="/eml" docBase="eml" debug="0" reloadbale="true" privileged="true">  
       
    <WatchedResource>WEB-INF/web.xml</WatchedResource>  
       
    <WatchedResource>WEB-INF/eml.xml</WatchedResource># monitoring resource file, if the web. XML | | eml. XML has changed, automatically change to reload the application.<Resource name="jdbc/testSiteds" &emsp; &emsp; # indicates the specifiedjndiThe name of theauth="Container" &emsp; &emsp; # indicates the authentication modeContainer  
    type="javax.sql.DataSource"  
    maxActive="100" &emsp; &emsp; # Maximum number of connections supported by the connection poolmaxIdle="40" &emsp; &emsp; &emsp; &emsp; The connection pool can be free at mostmaxIdleA connectionmaxWait="30000" &emsp; &emsp; New request wait time in milliseconds when connections in the pool run outusername="txl" &emsp; &emsp; &emsp; # indicates the database user namepassword="123456" &emsp; &emsp; # indicates the password of the database userdriverClassName="com.mysql.jdbc.Driver" &emsp; &emsp; # saidJDBC DRIVER  
    url="jdbc:mysql://localhost:3306/testSite" />&emsp; &emsp; # indicates the database URL</Context>
Copy the code
  • Web. XML :Web application description file, all about configuration files for Web applications.
  • Tomcat-users. XML :Tomcat Manager user configuration
  • Server. XML: you can set the port number, add virtual machines, etc., is the server Settings
<Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <Listener className="org.apache.catalina.security.SecurityListener" />
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" /> 
  <Listener className="org.apache.catalina.core.JasperListener" /> 
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" /> 
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" /> 
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" /> 
  <GlobalNamingResources> 
  <! Global named resources to define external access resources that are referenced by all engine applications. > <Resource name="UserDatabase" auth="Container" type="org.apache.catalina.UserDatabase" description="User database that  can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" pathname="conf/tomcat-users.xml" /> </GlobalNamingResources> <! Conf /tomcat-users. XML is loaded into memory to authenticate users when needed. 
  <Service name="Catalina"> 
  <! An Engine can be used for each Connector. Only one Engine can be used for each Service. > <Connector port="80" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" /> <! -- Change HTTP/1.1 Connector listening port to 80. Requests from clients accessed through browsers can only be sent to Tomcat through HTTP. You can also set the server and URIEncoding parameters --> 
    <Connector port="8009" protocol="AJP / 1.3" redirectPort="8443" /> 
    <Engine name="Catalina" defaultHost="test.com"> 
    <! -- change the current Engine, default host is www.test.com --> 
    <Realm className="org.apache.catalina.realm.LockOutRealm"> 
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm" 
               resourceName="UserDatabase"/> 
    </Realm>The # Realm component, which defines authentication for application access within the current container, through the external resource UserDatabase<Host name="test.com"  appBase="/web" unpackWARs="true" autoDeploy="true"> 
      <! Select * from test.com; select * from /web; select * from test.com; 
        <Alias>www.test.com</Alias> 
        <! -- Define an alias www.test.com, similar to apache ServerAlias --> 
        <Context path="" docBase="www/" reloadable="true" /> 
        <! -- Define the application, access path "", i.e. visit www.test.com, web directory is: /web/ WWW relative to WWW /, i.e., /web/ WWW, and automatically reloads the current configuration when there are changes to web.xml or classes etc. under the application, i.e., tomcat does not need to restart for the deployed new application to take effect --> 
        <Context path="/bbs" docBase="/web/bbs" reloadable="true" /> 
        <! -- Define another independent application (virtual host), access path: www.test.com/bbs, the application web directory is /web/ BBS --> 
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="/web/www/logs" 
               prefix="www_access." suffix=".log" 
               pattern="%h %l %u %t " %r" %s %b" /> 
        <! /web/ WWW /logs = $CATALINA_HOME, not appBase The log file is prefixed with www_access. The log file ends with.log. Pattern defines the log content format. 
      </Host> 
      <Host name="manager.test.com" appBase="webapps" unpackWARs="true" autoDeploy="true"> 
      <! $CATALINA_HOME/webapps = $CATALINA_HOME/webapps; 
        <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="172.16.100. *" /> 
        <! -- Define a remote address access policy that only 172.16.100.* network segment is allowed to access the host. 
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="/web/bbs/logs" 
               prefix="bbs_access." suffix=".log" 
               pattern="%h %l %u %t " %r" %s %b" /> 
        <! -- Define the host access log --> 
      </Host> 
    </Engine> 
  </Service> 
</Server>
Copy the code

1.Server element: the root element of the entire configuration file. Represents the entire Catalina container;

ClassName: implements the org. Apache. Catalina. The class name of the Server interface, the standard implementation class is org. Apache. Catalina. Core. StandardServer classes; Port: the Tomcat server listens for the command used to shut down the Tomcat server (mandatory). Shutdown: the command sent to the port to Shutdown the Tomcat server.Copy the code

2.Connector element: the Connector, which is responsible for receiving customer requests and sending back response information to the client; 3.Engine element: Handles all requests for a particular Service. Each Service can contain only one Engine element. It is responsible for receiving and processing all requests received by the connector of the Service, sending the response back to the connection, and finally displaying it on the client side. The Engine has at least one Host element and must have at least one Host attribute whose name matches the name specified by defaultHost. 4.Host element: represents a virtual Host, processing all requests for a specific virtual Host; 5. Context element: A Web application that handles all requests from the current Web application, and each context must use a unique context path.

2.1.1 Tomcat Multi-threaded processing of HTTP Requests

The thread pool

  thread = threadPool.getThread();
  thread.executeHttp(htttpRequest);
Copy the code

Get all controllers from each thread. Find the corresponding controllerobject according to the httprequest sent to the thread. Then the controller object starts executing.

2.2 Database Access

Mainly SQL processing and optimization.

To query a user, understand the following:

  • What are the specific functions?
  • What are the user request parameters?
  • Once the request has been sent, once the server has captured it, how does the server handle the request, and if there are a large number of requests at the same time?
  • How does Tomcat forward to different function bodies based on the router?
  • What is the implementation logic? Where are the main SQL queries represented?
  • How do you check? What are the optimizations?
  • What optimization points can the database have when the data quantity increases?
  • After the data is processed, how is it encapsulated and returned?

3. Think about a few questions

For large websites, the main problems are as follows: 1. Large volume of visits 2

  • How can I solve the problem that the load on a single server is too high? — (Server cluster)
  • If the number of users increases, how can the server ease the load when multiple HTTP requests are sent simultaneously? — (High concurrency)
  • What can I do if the amount of data in the database is too high? How should the database respond to multiple query operations? — (database cache)

4. The optimal point

4.1 the cluster

Problem: When the number of users increases, the load on a single server is too high, which accelerates hardware aging.

Solution: 1. Separate the database server from services. Separate the database server; If the application server is down, the database is not affected.

Distribution is to shorten the execution time of a single task to improve efficiency; Clustering improves efficiency by increasing the number of tasks executed per unit time. Clusters are divided into: High Availability Cluster, Load Balance Cluster (nGINx), and High Performance Computing Cluster; Distributed refers to the distribution of different services in different places; Clustering refers to the concentration of several servers to implement the same service. Each node in the distributed system can be a cluster. And clustering doesn't have to be distributed; Each large website will have different architectural patterns, and architectural content is dealing with load balancing, caching, database, file system, etc., but in different environments, different conditions, the architectural model is not the same, the purpose is to improve the performance of the website. Reference: https://www.cnblogs.com/liangxiaofeng/p/4920267.htmlCopy the code





4.2 Load Balancing

Question: How can the server mitigate the increase in the number of users and send multiple HTTP requests simultaneously?

Solution: The purpose of load balancing is to get requests to different servers. There are so many steps between a request and the server that there are many ways to implement it. In practice, there are only a few ways.

  • HTTP redirected load balancing – not familiar
  • DNS Domain name resolution load balancing —
  • Reverse proxy load balancer
  • Network layer load balancing
  • Data link layer load balancing

4.3 Database cache optimization

Question: How can I solve the problem when the amount of data in the database is too high? How should the database respond to multiple query operations?

Solution: 1. Read/write separation of the database

How to operate database read/write separation; How to operate the data synchronization of database;

2. Search engines














The cache is divided into server cache and application cache. The cache server is read first, and the database server is read if there is no hit.

4. Horizontal/vertical split of the database

5. To summarize

  • Be familiar with the entire server process from browser request to response, especially with at least two of the modules, and understand the implementation mechanism.

  • The same business uses multiple servers, plus load balancing
  • Services are split and different servers provide different services
  • Database split, horizontal split, vertical split
  • Things that are dynamic are static, cached
  • Data caching, such as Redis cache, Redis cluster and so on

Reference: my.oschina.net/u/2543341/b… www.cnblogs.com/sunshine-1/… www.cnblogs.com/liangxiaofe…