美文网首页
Tomcat源码简要解析

Tomcat源码简要解析

作者: 知止9528 | 来源:发表于2019-01-23 19:37 被阅读0次

    Tomcat架构图


    tomcat架构图.png

    源码流程如下

    ###找到启动类
    org.apache.catalina.startup.Bootstrap.main()
     ->org.apache.catalina.startup.Bootstrap.init()
      ->org.apache.catalina.startup.Catalina.load()
       ->org.apache.catalina.startup.Catalina.createStartDigester()  解析xml文件
      ->org.apache.catalina.startup.Catalina.getServer()   
       ->org.apache.catalina.util.LifecycleBase.init()
        ->org.apache.catalina.core.StandardServer.initInternal()  备注,这里的是StandardServer
        // Initialize our defined Services
        for (int i = 0; i < services.length; i++) {
           services[i].init();
        }
        
         ->org.apache.catalina.util.LifecycleBase.init()
          ->org.apache.catalina.core.StandardService.initInternal() 备注,这里的是StandardService
           ->engine.init();
           ->executor.init();   在for循环里面初始化,即executor有多个
           ->mapperListener.init();
           ->connector.init();  在for循环里面初始化  即connector有多个
            ->org.apache.catalina.connector.Connector.initInternal() 
             ->protocolHandler.init();
              ->org.apache.coyote.AbstractProtocol.init()
               ->org.apache.tomcat.util.net.AbstractEndpoint.init()
                ->org.apache.tomcat.util.net.AbstractEndpoint.bindWithCleanup()
                 ->org.apache.tomcat.util.net.NioEndpoint.bind()
                  ->org.apache.tomcat.util.net.NioEndpoint.initServerSocket()
                   ->serverSock.socket().bind(addr,getAcceptCount());  调用socket.bind()
           
    

    整个启动流程图如下:


    Tomcat启动流程图.png

    结构图如下


    Tomcat结构图.png

    小结

    我们常用的如下

    public class LoginServlet extends  MyServlet {
        @Override
        void service(MyTomcat.Request request, MyTomcat.Response response) {
    
        }
    }
    

    那么Tomcat容器到底是什么?

    伪代码如下

    public class MyTomcat {
            //1.网络连接
            ServerSocket serverSocket = new ServerSocket(8080);
            Socket accept = serverSocket.accept();
    
            List<MyServlet> list = new ArrayList<>();
    
            //2.根据连接获取输入输出
            InputStream in = accept.getInputStream();
            Request request = new Request(in);
            OutputStream out = accept.getOutputStream();
            Response response = new Response(out);
    
            //解析xml文件  添加servlet
            //LoginServlet loginServlet = new LoginServlet();
            list.add(loginServlet);
    }
    

    将请求和响应封装,提供统一的抽象方法

    public abstract  class MyServlet {
        abstract void  service(MyTomcat.Request request, MyTomcat.Response response);
    }
    

    相关文章

      网友评论

          本文标题:Tomcat源码简要解析

          本文链接:https://www.haomeiwen.com/subject/yyvjjqtx.html