美文网首页
Tomcat源码分析(二)

Tomcat源码分析(二)

作者: 我是嘻哈大哥 | 来源:发表于2019-04-26 19:50 被阅读0次

    1.程序入口

    Bootstrap.java的main方法
    关键语句:

        public static void main(String args[]) {
    
            if (daemon == null) {
                // Don't set daemon until init() has completed
                //创建对象
                Bootstrap bootstrap = new Bootstrap();
                try {
                    //初始化bootstrap
                    bootstrap.init();
                } catch (Throwable t) {
                    handleThrowable(t);
                    t.printStackTrace();
                    return;
                }
                daemon = bootstrap;
            } else {
                // When running as a service the call to stop will be on a new
                // thread so make sure the correct class loader is used to prevent
                // a range of class not found exceptions.
                Thread.currentThread().setContextClassLoader(daemon.catalinaLoader);
            }
    
            try {
                String command = "start";
                if (args.length > 0) {
                    command = args[args.length - 1];
                }
    
                if (command.equals("startd")) {
                    args[args.length - 1] = "start";
                    daemon.load(args);
                    daemon.start();
                } else if (command.equals("stopd")) {
                    args[args.length - 1] = "stop";
                    daemon.stop();
                } else if (command.equals("start")) {
                    daemon.setAwait(true);
                    //装在参数
                    daemon.load(args);
                    //开始启动
                    daemon.start();
                    if (null == daemon.getServer()) {
                        System.exit(1);
                    }
                } else if (command.equals("stop")) {
                    daemon.stopServer(args);
                } else if (command.equals("configtest")) {
                    daemon.load(args);
                    if (null == daemon.getServer()) {
                        System.exit(1);
                    }
                    System.exit(0);
                } else {
                    log.warn("Bootstrap: command \"" + command + "\" does not exist.");
                }
            } catch (Throwable t) {
                // Unwrap the Exception for clearer error reporting
                if (t instanceof InvocationTargetException &&
                        t.getCause() != null) {
                    t = t.getCause();
                }
                handleThrowable(t);
                t.printStackTrace();
                System.exit(1);
            }
    
        }
    

    2.程序分析

    --------------------------设置环境变量----------------------------------
    >Bootstrap下的静态代码块;//定义Globals.CATALINA_HOME_PROP和Globals.CATALINA_BASE_PROP环境变量
    >Bootstrap bootstrap = new Bootstrap();
    
    --------------------------init()----------------------------------
    >bootstrap.init();
    >initClassLoaders();
    >commonLoader = createClassLoader("common", null);
    >CatalinaProperties.getProperty(name + ".loader");//装载.loader文件
    >loadProperties();//CatalinaProperties静态代码块,主要是解析装载/conf/catalina.properties文件
    >ClassLoaderFactory.createClassLoader(repositories, parent);//创建类加载器
    >return new URLClassLoader(array);//array是lib文件夹下的jar的url
    
    --------------------------load()----------------------------------
    >daemon.load(args);
    >method.invoke(catalinaDaemon, param);//调用catalina的load方法
    >Digester digester = createStartDigester(); //创建和执行破壳器
    >digester.addObjectCreate("Server","org.apache.catalina.core.StandardServer","className");//基于StandardServer创建Server对象
    >digester.addSetProperties("Server");//设置属性
    >digester.addSetNext("Server","setServer","org.apache.catalina.Server");//执行setServer方法
    >digester.parse(inputSource); //使用破壳器解析server.xml,**重要**
    
    --------------------------初始化容器----------------------------------
    >getServer().init(); //初始化server
    >LefecycleBase.initInternal();//调用基类的initInternal方法
    >StanderServer.initInternal();//调用StanderServer的initInternal方法
    >services[i].init(); //调用services的init方法
    
    >LefecycleBase.initInternal();//调用基类的initInternal方法
    >StanderService.initInternal();//调用StanderService的initInternal方法
    >engine.init();//调用engine的init方法
    
    >LefecycleBase.initInternal();//调用基类的initInternal方法
    >StanderEngine.initInternal();//调用StanderEngine的initInternal方法
    >super.initInternal();
    >startStopExecutor = new ThreadPoolExecutor(getStartStopThreadsInternal(),getStartStopThreadsInternal(), 10, TimeUnit.SECONDS,startStopQueue,new StartStopThreadFactory(getName() + "-startStop-"));//创建线程池
    
    --------------------------初始化executor----------------------------------
    >executor.init();//执行器初始化
    
    --------------------------初始化mapperListener----------------------------------
    >mapperListener.init();//映射监听器初始化
    >LifecycleMBeanBase.initInternal();
    
    --------------------------初始化connector----------------------------------
    >connector.init();//连接器初始化
    >Connector.initInternal();
    >adapter = new CoyoteAdapter(this);//适配器
    >protocolHandler.setAdapter(adapter);//协议适配器
    >protocolHandler.init();
    >AbstractHttp11Protocol.init();
    >endpoint.init(); //端点初始化
    
    --------------------------start()----------------------------------
    >daemon.start();//启动
    >method.invoke(catalinaDaemon, (Object [])null); //调用catalina的start方法
    >start();
    >getServer().start();//启动server
    >LefecycleBase.start();//
    >startInternal();//
    >StandardServer.startInternal()//调用StandardServer启动
    >globalNamingResources.start();
    >services[i].start();//启动service
    >LefecycleBase.start();
    >startInternal();
    >stanardservice.startInternal();//调用stanardservice启动
    
    --------------------------启动engine----------------------------------
    >engine.start();//启动engine
    >results.add(startStopExecutor.submit(new StartChild(children[i])));
    >child.start();
    >StandardHost.startInternal()
    >setState(LifecycleState.STARTING);//ContainerBase.java
    >fireLifecycleEvent(lifecycleEvent, data);
    >lifecycleEvent()//HostConfig
    >start();
    >deployApps();   //部署webapp  
    
    --------------------------启动executor----------------------------------
    >executor.start();//启动执行器
    
    --------------------------启动connector----------------------------------
    >connector.start();//启动连接器
    >lefcycleBase.start();
    >Connector.startInternal();
    >protocolHandler.start();//协议处理器启动
    >AbstractProtocol.start();
    >endpoint.start();//端点启动
    >AbstractEndpoint.start();
    >startInternal();
    >NioEndpoint.startInternal();//NioEndpoint启动
    >pollerThread.start();//poller线程启动
    >poller.run();
    >processKey(sk, attachment);//接收到请求进入此方法
    >processSocket(attachment, SocketEvent.OPEN_READ, true);
    >createSocketProcessor(socketWrapper, event);//创建SocketProcessor
    >return new SocketProcessor(socketWrapper, event);
    >SocketProcessorBase.run();
    >SocketProcessor.doRun();//运行SocketProcessor
    >state = getHandler().process(socketWrapper, SocketEvent.OPEN_READ);//
    >state = processor.process(wrapper, status);
    >state = service(socketWrapper);
    >http11Processor.service();//http11Processor 
    >getAdapter().service(request, response);//
    >CoyoteAdapter.service(request, response);//适配器执行service方法
    >postParseSuccess = postParseRequest(req, request, res, response);//解析请求
    >connector.getService().getMapper().map(serverName, decodedURI,version, request.getMappingData());//请求路径映射
    >connector.getService().getContainer().getPipeline().getFirst().invoke(request, response);//调用第一个container的valve
    >StandardEngineValve.invoke(request, response);
    >host.getPipeline().getFirst().invoke(request, response);//调用host容器
    >StandardHostValve.invoke(request, response);
    >context.getPipeline().getFirst().invoke(request, response);//调用context容器
    >StandardContextValve.invoke(request, response);
    >wrapper.getPipeline().getFirst().invoke(request, response);//调用wrapper
    >StandardWrapperValve.invoke(request, response);
    >servlet = wrapper.allocate();
    >ApplicationFilterChain filterChain =ApplicationFilterFactory.createFilterChain(request, wrapper, servlet);//创建过滤器链
    >filterChain.doFilter(request.getRequest(), response.getResponse());
    >internalDoFilter(request,response);
    >filter.doFilter(request, response, this);
    >chain.doFilter(request, response);
    >internalDoFilter(request,response);
    >servlet.service(request, response);//servlet执行service方法
    
    >filterChain.release();//释放filterChain
    >wrapper.deallocate(servlet);//释放wrapper
    
    --------------------------阻塞等待----------------------------------
    >await();
    >StandardServer.await();
    >awaitSocket = new ServerSocket(port, 1,InetAddress.getByName(address));//port 8005
    >socket = serverSocket.accept();//阻塞等待
    >
    

    相关文章

      网友评论

          本文标题:Tomcat源码分析(二)

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