1. 程式人生 > 程式設計 >Tomcat在SpringBoot中是如何啟動的

Tomcat在SpringBoot中是如何啟動的

image

前言

我們知道SpringBoot給我們帶來了一個全新的開發體驗,我們可以直接把web程式達成jar包,直接啟動,這就得益於SpringBoot內建了容器,可以直接啟動,本文將以Tomcat為例,來看看SpringBoot是如何啟動Tomcat的,同時也將展開學習下Tomcat的原始碼,瞭解Tomcat的設計。

從 Main 方法說起

用過SpringBoot的人都知道,首先要寫一個main方法來啟動

@SpringBootApplication
public class TomcatdebugApplication {

    public static void main(String[] args) {
        SpringApplication.run(TomcatdebugApplication.class,args);
    }

}
複製程式碼

我們直接點選run方法的原始碼,跟蹤下來,發下最終 的run方法是呼叫ConfigurableApplicationContext方法,原始碼如下:

public ConfigurableApplicationContext run(String... args) {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		ConfigurableApplicationContext context = null;
		Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
		//設定系統屬性『java.awt.headless』,為true
則啟用headless模式支援 configureHeadlessProperty(); //通過*SpringFactoriesLoader*檢索*META-INF/spring.factories*, //找到宣告的所有SpringApplicationRunListener的實現類並將其例項化, //之後逐個呼叫其started()方法,廣播SpringBoot要開始執行了 SpringApplicationRunListeners listeners = getRunListeners(args); //釋出應用開始啟動事件 listeners.starting(); try { //初始化引數 ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); //建立並配置當前SpringBoot應用將要使用的Environment(包括配置要使用的PropertySource以及Profile),//並遍歷呼叫所有的SpringApplicationRunListener的environmentPrepared()方法,廣播Environment準備完畢。 ConfigurableEnvironment environment = prepareEnvironment(listeners,applicationArguments); configureIgnoreBeanInfo(environment); //列印banner Banner printedBanner = print
Banner(environment); //建立應用上下文 context = createApplicationContext(); //通過*SpringFactoriesLoader*檢索*META-INF/spring.factories*,獲取並例項化異常分析器 exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,new Class[] { ConfigurableApplicationContext.class },context); //為ApplicationContext載入environment,之後逐個執行ApplicationContextInitializer的initialize()方法來進一步封裝ApplicationContext, //並呼叫所有的SpringApplicationRunListener的contextPrepared()方法,【EventPublishingRunListener只提供了一個空的contextPrepared()方法】, //之後初始化IoC容器,並呼叫SpringApplicationRunListener的contextLoaded()方法,廣播ApplicationContext的IoC載入完成, //這裡就包括通過**@EnableAutoConfiguration**匯入的各種自動配置類。 prepareContext(context,environment,listeners,applicationArguments,printedBanner); //重新整理上下文 refreshContext(context); //再一次重新整理上下文,其實是空方法,可能是為了後續擴充套件。 afterRefresh(context,applicationArguments); stopWatch.stop(); if (this.logStartupInfo) { new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(),stopWatch); } //釋出應用已經啟動的事件 listeners.started(context); //遍歷所有註冊的ApplicationRunner和CommandLineRunner,並執行其run()方法。 //我們可以實現自己的ApplicationRunner或者CommandLineRunner,來對SpringBoot的啟動過程進行擴充套件。 callRunners(context,applicationArguments); } catch (Throwable ex) { handleRunFailure(context,ex,exceptionReporters,listeners); throw new IllegalStateException(ex); } try { //應用已經啟動完成的監聽事件 listeners.running(context); } catch (Throwable ex) { handleRunFailure(context,null); throw new IllegalStateException(ex); } return context; } 複製程式碼

其實這個方法我們可以簡單的總結下步驟為

  1. 配置屬性
  2. 獲取監聽器,釋出應用開始啟動事件
  3. 初始化輸入引數
  4. 配置環境,輸出banner
  5. 建立上下文
  6. 預處理上下文
  7. 重新整理上下文
  8. 再重新整理上下文
  9. 釋出應用已經啟動事件
  10. 釋出應用啟動完成事件

其實上面這段程式碼,如果只要分析tomcat內容的話,只需要關注兩個內容即可,上下文是如何建立的,上下文是如何重新整理的,分別對應的方法就是createApplicationContext()refreshContext(context),接下來我們來看看這兩個方法做了什麼。

protected ConfigurableApplicationContext createApplicationContext() {
		Class<?> contextClass = this.applicationContextClass;
		if (contextClass == null) {
			try {
				switch (this.webApplicationType) {
				case SERVLET:
					contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
					break;
				case REACTIVE:
					contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
					break;
				default:
					contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
				}
			}
			catch (ClassNotFoundException ex) {
				throw new IllegalStateException(
						"Unable create a default ApplicationContext," + "please specify an ApplicationContextClass",ex);
			}
		}
		return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
	}
複製程式碼

這裡就是根據我們的webApplicationType 來判斷建立哪種型別的Servlet,程式碼中分別對應著Web型別(SERVLET),響應式Web型別(REACTIVE),非Web型別(default),我們建立的是Web型別,所以肯定例項化 DEFAULT_SERVLET_WEB_CONTEXT_CLASS指定的類,也就是AnnotationConfigServletWebServerApplicationContext類,我們來用圖來說明下這個類的關係

通過這個類圖我們可以知道,這個類繼承的是ServletWebServerApplicationContext,這就是我們真正的主角,而這個類最終是繼承了AbstractApplicationContext,瞭解完建立上下文的情況後,我們再來看看重新整理上下文,相關程式碼如下:

//類:SpringApplication.java

private void refreshContext(ConfigurableApplicationContext context) {
    //直接呼叫重新整理方法
		refresh(context);
		if (this.registerShutdownHook) {
			try {
				context.registerShutdownHook();
			}
			catch (AccessControlException ex) {
				// Not allowed in some environments.
			}
		}
	}
//類:SpringApplication.java

protected void refresh(ApplicationContext applicationContext) {
		Assert.isInstanceOf(AbstractApplicationContext.class,applicationContext);
		((AbstractApplicationContext) applicationContext).refresh();
	}
複製程式碼

這裡還是直接傳遞呼叫本類的refresh(context)方法,最後是強轉成父類AbstractApplicationContext呼叫其refresh()方法,該程式碼如下:

// 類:AbstractApplicationContext	
public void refresh() throws BeansException,IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				initMessageSource();

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.這裡的意思就是呼叫各個子類的onRefresh()
				onRefresh();

				// Check for listener beans and register them.
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				finishRefresh();
			}

			catch (BeansException ex) {
				if (logger.isWarnEnabled()) {
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}

				// Destroy already created singletons to avoid dangling resources.
				destroyBeans();

				// Reset 'active' flag.
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}

			finally {
				// Reset common introspection caches in Spring's core,since we
				// might not ever need metadata for singleton beans anymore...
				resetCommonCaches();
			}
		}
	}

複製程式碼

這裡我們看到onRefresh()方法是呼叫其子類的實現,根據我們上文的分析,我們這裡的子類是ServletWebServerApplicationContext

//類:ServletWebServerApplicationContext
protected void onRefresh() {
		super.onRefresh();
		try {
			createWebServer();
		}
		catch (Throwable ex) {
			throw new ApplicationContextException("Unable to start web server",ex);
		}
	}
	
private void createWebServer() {
		WebServer webServer = this.webServer;
		ServletContext servletContext = getServletContext();
		if (webServer == null && servletContext == null) {
			ServletWebServerFactory factory = getWebServerFactory();
			this.webServer = factory.getWebServer(getSelfInitializer());
		}
		else if (servletContext != null) {
			try {
				getSelfInitializer().onStartup(servletContext);
			}
			catch (ServletException ex) {
				throw new ApplicationContextException("Cannot initialize servlet context",ex);
			}
		}
		initPropertySources();
	}

複製程式碼

到這裡,其實廬山真面目已經出來了,createWebServer()就是啟動web服務,但是還沒有真正啟動Tomcat,既然webServer是通過ServletWebServerFactory來獲取的,我們就來看看這個工廠的真面目。

走進Tomcat內部

根據上圖我們發現,工廠類是一個介面,各個具體服務的實現是由各個子類來實現的,所以我們就去看看TomcatServletWebServerFactory.getWebServer()的實現。

	@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 = 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);
	}
複製程式碼

根據上面的程式碼,我們發現其主要做了兩件事情,第一件事就是把Connnctor(我們稱之為聯結器)物件新增到Tomcat中,第二件事就是configureEngine,這聯結器我們勉強能理解(不理解後面會述說),那這個Engine是什麼呢?我們檢視tomcat.getEngine()的原始碼:

    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是容器,我們繼續跟蹤原始碼,找到Container介面

上圖中,我們看到了4個子介面,分別是Engine,Host,Context,Wrapper。我們從繼承關係上可以知道他們都是容器,那麼他們到底有啥區別呢?我看看他們的註釋是怎麼說的。

 /**
 If used,an Engine is always the top level Container in a Catalina
 * hierarchy. Therefore,the implementation's <code>setParent()</code> method
 * should throw <code>IllegalArgumentException</code>.
 *
 * @author Craig R. McClanahan
 */
public interface Engine extends Container {
    //省略程式碼
}
/**
 * <p>
 * The parent Container attached to a Host is generally an Engine,but may
 * be some other implementation,or may be omitted if it is not necessary.
 * <p>
 * The child containers attached to a Host are generally implementations
 * of Context (representing an individual servlet context).
 *
 * @author Craig R. McClanahan
 */
public interface Host extends Container {
//省略程式碼
    
}
/*** <p>
 * The parent Container attached to a Context is generally a Host,or may be omitted if it is not necessary.
 * <p>
 * The child containers attached to a Context are generally implementations
 * of Wrapper (representing individual servlet definitions).
 * <p>
 *
 * @author Craig R. McClanahan
 */
public interface Context extends Container,ContextBind {
    //省略程式碼
}
/**<p>
 * The parent Container attached to a Wrapper will generally be an
 * implementation of Context,representing the servlet context (and
 * therefore the web application) within which this servlet executes.
 * <p>
 * Child Containers are not allowed on Wrapper implementations,so the
 * <code>addChild()</code> method should throw an
 * <code>IllegalArgumentException</code>.
 *
 * @author Craig R. McClanahan
 */
public interface Wrapper extends Container {

    //省略程式碼
}

複製程式碼

上面的註釋翻譯過來就是,Engine是最高階別的容器,其子容器是Host,Host的子容器是Context,WrapperContext的子容器,所以這4個容器的關係就是父子關係,也就是Engine>Host>Context>Wrapper。 我們再看看Tomcat類的原始碼:

//部分原始碼,其餘部分省略。
public class Tomcat {
//設定聯結器
     public void setConnector(Connector connector) {
        Service service = getService();
        boolean found = false;
        for (Connector serviceConnector : service.findConnectors()) {
            if (connector == serviceConnector) {
                found = true;
            }
        }
        if (!found) {
            service.addConnector(connector);
        }
    }
    //獲取service
       public Service getService() {
        return getServer().findServices()[0];
    }
    //設定Host容器
     public void setHost(Host host) {
        Engine engine = getEngine();
        boolean found = false;
        for (Container engineHost : engine.findChildren()) {
            if (engineHost == host) {
                found = true;
            }
        }
        if (!found) {
            engine.addChild(host);
        }
    }
    //獲取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;
    }
    //獲取server
       public Server getServer() {

        if (server != null) {
            return server;
        }

        System.setProperty("catalina.useNaming","false");

        server = new StandardServer();

        initBaseDir();

        // Set configuration source
        ConfigFileLoader.setSource(new CatalinaBaseConfigurationSource(new File(basedir),null));

        server.setPort( -1 );

        Service service = new StandardService();
        service.setName("Tomcat");
        server.addService(service);
        return server;
    }
    
    //新增Context容器
      public Context addContext(Host host,String contextPath,String contextName,String dir) {
        silence(host,contextName);
        Context ctx = createContext(host,contextPath);
        ctx.setName(contextName);
        ctx.setPath(contextPath);
        ctx.setDocBase(dir);
        ctx.addLifecycleListener(new FixContextListener());

        if (host == null) {
            getHost().addChild(ctx);
        } else {
            host.addChild(ctx);
        }
        
    //新增Wrapper容器
         public static Wrapper addServlet(Context ctx,String servletName,Servlet servlet) {
        // will do class for name and set init params
        Wrapper sw = new ExistingStandardWrapper(servlet);
        sw.setName(servletName);
        ctx.addChild(sw);

        return sw;
    }
    
}
複製程式碼

閱讀TomcatgetServer()我們可以知道,Tomcat的最頂層是Server,Server就是Tomcat的例項,一個Tomcat一個Server;通過getEngine()我們可以瞭解到Server下面是Service,而且是多個,一個Service代表我們部署的一個應用,而且我們還可以知道,Engine容器,一個service只有一個;根據父子關係,我們看setHost()原始碼可以知道,host容器有多個;同理,我們發現addContext()原始碼下,Context也是多個;addServlet()表明Wrapper容器也是多個,而且這段程式碼也暗示了,其實WrapperServlet是一層意思。另外我們根據setConnector原始碼可以知道,聯結器(Connector)是設定在service下的,而且是可以設定多個聯結器(Connector)。

根據上面分析,我們可以小結下: Tomcat主要包含了2個核心元件,聯結器(Connector)和容器(Container),用圖表示如下:

一個Tomcat是一個Server,一個Server下有多個service,也就是我們部署的多個應用,一個應用下有多個聯結器(Connector)和一個容器(Container),容器下有多個子容器,關係用圖表示如下:

Engine下有多個Host子容器,Host下有多個Context子容器,Context下有多個Wrapper子容器。

總結

SpringBoot的啟動是通過new SpringApplication()例項來啟動的,啟動過程主要做如下幾件事情:

  1. 配置屬性
  2. 獲取監聽器,釋出應用開始啟動事件
  3. 初始化輸入引數
  4. 配置環境,輸出banner
  5. 建立上下文
  6. 預處理上下文
  7. 重新整理上下文
  8. 再重新整理上下文
  9. 釋出應用已經啟動事件
  10. 釋出應用啟動完成事件

而啟動Tomcat就是在第7步中“重新整理上下文”;Tomcat的啟動主要是初始化2個核心元件,聯結器(Connector)和容器(Container),一個Tomcat例項就是一個Server,一個Server包含多個Service,也就是多個應用程式,每個Service包含多個聯結器(Connetor)和一個容器(Container),而容器下又有多個子容器,按照父子關係分別為:Engine,Wrapper,其中除了Engine外,其餘的容器都是可以有多個。

下期展望

本期文章通過SpringBoot的啟動來窺探了Tomcat的內部結構,下一期,我們來分析下本次文章中的聯結器(Connetor)和容器(Container)的作用,敬請期待。

版權宣告:原創文章,轉載請註明出處。