首页 > 编程技术 > java

SpringBoot嵌入式Web容器原理与使用介绍

发布时间:2022-10-24 15:53 作者:刘婉晴

嵌入式 Web 容器:应用中内置服务器(Tomcat),不用在外部配置服务器了

原理

ServletWebServerFactoryConfiguration.class

	@Override
	public WebServer getWebServer(ServletContextInitializer... initializers) {
		if (this.disableMBeanRegistry) {
			Registry.disableRegistry();
		}
		Tomcat tomcat = new Tomcat();
		File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");
		tomcat.setBaseDir(baseDir.getAbsolutePath());
		Connector connector = new Connector(this.protocol);
		connector.setThrowOnFailure(true);
		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);
	}

总结: 所谓内嵌服务器,就是把我们手动启动服务器的方法放进框架中了。

应用

1. 切换Web服务器

排除 tomcat 服务器,导入 undertow 依赖

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>

2. 定制服务器规则

方法一: 修改 server 下的配置文件

ServerProperties.class

server.undertow.accesslog.dir=/tmp

方法二: 自定义 ConfigurableServletWebServerFactory

方法三: 自定义 ServletWebServerFactoryCustomizer 定制化器

作用: 将配置文件的值,与 ServletWebServerFactory 绑定

SpringBoot 设计: Customizer 定制化器,可以定制 XXX 规则

到此这篇关于SpringBoot嵌入式Web容器原理与使用介绍的文章就介绍到这了,更多相关SpringBoot嵌入式Web容器内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

原文出处:https://blog.csdn.net/liuwanqing233333/article/details/12739

标签:[!--infotagslink--]

您可能感兴趣的文章: