總在說SpringBoot內置了tomcat啓動,那它的原理你說的清楚嗎?

關注Java後端技術全棧php

回覆「面試」獲取全套面試資料java

來源:http://suo.im/5KUDd2react

前言

不得不說SpringBoot的開發者是在爲大衆程序猿謀福利,把你們都慣成了懶漢,xml不配置了,連tomcat也懶的配置了,典型的一鍵啓動系統,那麼tomcat在springboot是怎麼啓動的呢?web

內置tomcat

開發階段對咱們來講使用內置的tomcat是很是夠用了,固然也可使用jetty。面試

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
   <version>2.1.6.RELEASE</version>
</dependency>
@SpringBootApplication
public class MySpringbootTomcatStarter{
    public static void main(String[] args) {
        Long time=System.currentTimeMillis();
        SpringApplication.run(MySpringbootTomcatStarter.class);
        System.out.println("===應用啓動耗時:"+(System.currentTimeMillis()-time)+"===");
    }
}

這裏是main函數入口,兩句代碼最耀眼,分別是SpringBootApplication註解和SpringApplication.run()方法。spring

發佈生產

發佈的時候,目前大多數的作法仍是排除內置的tomcat,打瓦包(war)而後部署在生產的tomcat中,好吧,那打包的時候應該怎麼處理?後端

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <!-- 移除嵌入式tomcat插件 -->
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<!--添加servlet-api依賴--->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

更新main函數,主要是繼承SpringBootServletInitializer,並重寫configure()方法。api

@SpringBootApplication
public class MySpringbootTomcatStarter extends SpringBootServletInitializer {
    public static void main(String[] args) {
        Long time=System.currentTimeMillis();
        SpringApplication.run(MySpringbootTomcatStarter.class);
        System.out.println("===應用啓動耗時:"+(System.currentTimeMillis()-time)+"===");
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(this.getClass());
    }
}

從main函數提及

public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
    return run(new Class[]{primarySource}, args);
}

--這裏run方法返回的是ConfigurableApplicationContext
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
 return (new SpringApplication(primarySources)).run(args);
}
public ConfigurableApplicationContext run(String... args) {
 ConfigurableApplicationContext context = null;
 Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
 this.configureHeadlessProperty();
 SpringApplicationRunListeners listeners = this.getRunListeners(args);
 listeners.starting();

 Collection exceptionReporters;
 try {
  ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
  ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
  this.configureIgnoreBeanInfo(environment);
  
  //打印banner,這裏你能夠本身塗鴉一下,換成本身項目的logo
  Banner printedBanner = this.printBanner(environment);
  
  //建立應用上下文
  context = this.createApplicationContext();
  exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);

  //預處理上下文
  this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
  
  //刷新上下文
  this.refreshContext(context);
  
  //再刷新上下文
  this.afterRefresh(context, applicationArguments);
  
  listeners.started(context);
  this.callRunners(context, applicationArguments);
 } catch (Throwable var10) {
  
 }

 try {
  listeners.running(context);
  return context;
 } catch (Throwable var9) {
  
 }
}

既然咱們想知道tomcat在SpringBoot中是怎麼啓動的,那麼run方法中,重點關注建立應用上下文(createApplicationContext)和刷新上下文(refreshContext)。tomcat

建立上下文

//建立上下文
protected ConfigurableApplicationContext createApplicationContext() {
 Class<?> contextClass = this.applicationContextClass;
 if (contextClass == null) {
  try {
   switch(this.webApplicationType) {
    case SERVLET:
                    //建立AnnotationConfigServletWebServerApplicationContext
        contextClass = Class.forName("org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext");
     break;
    case REACTIVE:
     contextClass = Class.forName("org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext");
     break;
    default:
     contextClass = Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext");
   }
  } catch (ClassNotFoundException var3) {
   throw new IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", var3);
  }
 }

 return (ConfigurableApplicationContext)BeanUtils.instantiateClass(contextClass);
}

這裏會建立AnnotationConfigServletWebServerApplicationContext類。而AnnotationConfigServletWebServerApplicationContext類繼承了ServletWebServerApplicationContext,而這個類是最終集成了AbstractApplicationContext。springboot

刷新上下文

//SpringApplication.java
//刷新上下文
private void refreshContext(ConfigurableApplicationContext context) {
 this.refresh(context);
 if (this.registerShutdownHook) {
  try {
   context.registerShutdownHook();
  } catch (AccessControlException var3) {
  }
 }
}

//這裏直接調用最終父類AbstractApplicationContext.refresh()方法
protected void refresh(ApplicationContext applicationContext) {
 ((AbstractApplicationContext)applicationContext).refresh();
}
//AbstractApplicationContext.java
public void refresh() throws BeansException, IllegalStateException {
 synchronized(this.startupShutdownMonitor) {
  this.prepareRefresh();
  ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
  this.prepareBeanFactory(beanFactory);

  try {
   this.postProcessBeanFactory(beanFactory);
   this.invokeBeanFactoryPostProcessors(beanFactory);
   this.registerBeanPostProcessors(beanFactory);
   this.initMessageSource();
   this.initApplicationEventMulticaster();
   //調用各個子類的onRefresh()方法,也就說這裏要回到子類:ServletWebServerApplicationContext,調用該類的onRefresh()方法
   this.onRefresh();
   this.registerListeners();
   this.finishBeanFactoryInitialization(beanFactory);
   this.finishRefresh();
  } catch (BeansException var9) {
   this.destroyBeans();
   this.cancelRefresh(var9);
   throw var9;
  } finally {
   this.resetCommonCaches();
  }

 }
}
//ServletWebServerApplicationContext.java
//在這個方法裏看到了熟悉的面孔,this.createWebServer,神祕的面紗就要揭開了。
protected void onRefresh() {
 super.onRefresh();
 try {
  this.createWebServer();
 } catch (Throwable var2) {
  
 }
}

//ServletWebServerApplicationContext.java
//這裏是建立webServer,可是尚未啓動tomcat,這裏是經過ServletWebServerFactory建立,那麼接着看下ServletWebServerFactory
private void createWebServer() {
 WebServer webServer = this.webServer;
 ServletContext servletContext = this.getServletContext();
 if (webServer == null && servletContext == null) {
  ServletWebServerFactory factory = this.getWebServerFactory();
  this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});
 } else if (servletContext != null) {
  try {
   this.getSelfInitializer().onStartup(servletContext);
  } catch (ServletException var4) {
  
  }
 }

 this.initPropertySources();
}

//接口
public interface ServletWebServerFactory {
    WebServer getWebServer(ServletContextInitializer... initializers);
}

//實現
AbstractServletWebServerFactory
JettyServletWebServerFactory
TomcatServletWebServerFactory
UndertowServletWebServerFactory

這裏ServletWebServerFactory接口有4個實現類

而其中咱們經常使用的有兩個:TomcatServletWebServerFactory和JettyServletWebServerFactory。

//TomcatServletWebServerFactory.java
//這裏咱們使用的tomcat,因此咱們查看TomcatServletWebServerFactory。到這裏總算是看到了tomcat的蹤影。
@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {
 Tomcat tomcat = new Tomcat();
 File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");
 tomcat.setBaseDir(baseDir.getAbsolutePath());
    //建立Connector對象
 Connector connector = new Connector(this.protocol);
 tomcat.getService().addConnector(connector);
 customizeConnector(connector);
 tomcat.setConnector(connector);
 tomcat.getHost().setAutoDeploy(false);
 configureEngine(tomcat.getEngine());
 for (Connector additionalConnector : this.additionalTomcatConnectors) {
  tomcat.getService().addConnector(additionalConnector);
 }
 prepareContext(tomcat.getHost(), initializers);
 return getTomcatWebServer(tomcat);
}

protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
 return new TomcatWebServer(tomcat, getPort() >= 0);
}

//Tomcat.java
//返回Engine容器,看到這裏,若是熟悉tomcat源碼的話,對engine不會感到陌生。
public Engine getEngine() {
    Service service = getServer().findServices()[0];
    if (service.getContainer() != null) {
        return service.getContainer();
    }
    Engine engine = new StandardEngine();
    engine.setName( "Tomcat" );
    engine.setDefaultHost(hostname);
    engine.setRealm(createDefaultRealm());
    service.setContainer(engine);
    return engine;
}
//Engine是最高級別容器,Host是Engine的子容器,Context是Host的子容器,Wrapper是Context的子容器

getWebServer這個方法建立了Tomcat對象,而且作了兩件重要的事情:把Connector對象添加到tomcat中,configureEngine(tomcat.getEngine());

getWebServer方法返回的是TomcatWebServer。

//TomcatWebServer.java
//這裏調用構造函數實例化TomcatWebServer
public TomcatWebServer(Tomcat tomcat, boolean autoStart) {
 Assert.notNull(tomcat, "Tomcat Server must not be null");
 this.tomcat = tomcat;
 this.autoStart = autoStart;
 initialize();
}

private void initialize() throws WebServerException {
    //在控制檯會看到這句日誌
 logger.info("Tomcat initialized with port(s): " + getPortsDescription(false));
 synchronized (this.monitor) {
  try {
   addInstanceIdToEngineName();

   Context context = findContext();
   context.addLifecycleListener((event) -> {
    if (context.equals(event.getSource()) && Lifecycle.START_EVENT.equals(event.getType())) {
     removeServiceConnectors();
    }
   });

   //===啓動tomcat服務===
   this.tomcat.start();

   rethrowDeferredStartupExceptions();

   try {
    ContextBindings.bindClassLoader(context, context.getNamingToken(), getClass().getClassLoader());
   }
   catch (NamingException ex) {
                
   }
            
            //開啓阻塞非守護進程
   startDaemonAwaitThread();
  }
  catch (Exception ex) {
   stopSilently();
   destroySilently();
   throw new WebServerException("Unable to start embedded Tomcat", ex);
  }
 }
}
//Tomcat.java
public void start() throws LifecycleException {
 getServer();
 server.start();
}
//這裏server.start又會回到TomcatWebServer的
public void stop() throws LifecycleException {
 getServer();
 server.stop();
}
//TomcatWebServer.java
//啓動tomcat服務
@Override
public void start() throws WebServerException {
 synchronized (this.monitor) {
  if (this.started) {
   return;
  }
  try {
   addPreviouslyRemovedConnectors();
   Connector connector = this.tomcat.getConnector();
   if (connector != null && this.autoStart) {
    performDeferredLoadOnStartup();
   }
   checkThatConnectorsHaveStarted();
   this.started = true;
   //在控制檯打印這句日誌,若是在yml設置了上下文,這裏會打印
   logger.info("Tomcat started on port(s): " + getPortsDescription(true) + " with context path '"
     + getContextPath() + "'");
  }
  catch (ConnectorStartFailedException ex) {
   stopSilently();
   throw ex;
  }
  catch (Exception ex) {
   throw new WebServerException("Unable to start embedded Tomcat server", ex);
  }
  finally {
   Context context = findContext();
   ContextBindings.unbindClassLoader(context, context.getNamingToken(), getClass().getClassLoader());
  }
 }
}

//關閉tomcat服務
@Override
public void stop() throws WebServerException {
 synchronized (this.monitor) {
  boolean wasStarted = this.started;
  try {
   this.started = false;
   try {
    stopTomcat();
    this.tomcat.destroy();
   }
   catch (LifecycleException ex) {
    
   }
  }
  catch (Exception ex) {
   throw new WebServerException("Unable to stop embedded Tomcat", ex);
  }
  finally {
   if (wasStarted) {
    containerCounter.decrementAndGet();
   }
  }
 }
}

附:tomcat頂層結構圖

tomcat最頂層容器是Server,表明着整個服務器,一個Server包含多個Service。從上圖能夠看除Service主要包括多個Connector和一個Container。Connector用來處理鏈接相關的事情,並提供Socket到Request和Response相關轉化。

Container用於封裝和管理Servlet,以及處理具體的Request請求。那麼上文提到的Engine>Host>Context>Wrapper容器又是怎麼回事呢?咱們來看下圖:

綜上所述,一個tomcat只包含一個Server,一個Server能夠包含多個Service,一個Service只有一個Container,但有多個Connector,這樣一個服務能夠處理多個鏈接。

多個Connector和一個Container就造成了一個Service,有了Service就能夠對外提供服務了,可是Service要提供服務又必須提供一個宿主環境,那就非Server莫屬了,因此整個tomcat的聲明週期都由Server控制。

總結

SpringBoot的啓動主要是經過實例化SpringApplication來啓動的,啓動過程主要作了如下幾件事情:配置屬性、獲取監聽器,發佈應用開始啓動事件初、始化輸入參數、配置環境,輸出banner、建立上下文、預處理上下文、刷新上下文、再刷新上下文、發佈應用已經啓動事件、發佈應用啓動完成事件。

在SpringBoot中啓動tomcat的工做在刷新上下這一步。而tomcat的啓動主要是實例化兩個組件:Connector、Container,一個tomcat實例就是一個Server,一個Server包含多個Service,也就是多個應用程序,每一個Service包含多個Connector和一個Container,而一個Container下又包含多個子容器。

END

我知道你 「在看」

本文分享 CSDN - 田維常。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索