springboot2.3.1替换为其他的嵌入式servlet容器的详细方法
现阶段,springboot内嵌了Tomcat服务器,如果你不想使用Tomcat,springboot也是支持其他的服务器切换的。
如果你想了解底层springboot所支持的服务器你可以使用idea的快捷键快速按两次shift查询一个ServerProperties 的类,通过这个类你可以知道你想要了解的情况:
springboot里面支持的服务器有Jetty、Netty…等等,大家有兴趣的话可以百度一下。
接着通过在pom文件的视图依赖分析可以得知:
springboot里面的Tomcat是在spring-boot-starter-web下,所以我们如果需要切换服务器的话,需要先移除了spring-boot-starter-web里面的Tomcat依赖,再建立你想要切换的服务器。
<!--排除Tomcat starter--> <exclusions><exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId></exclusion> </exclusions> </dependency> <!--引入其他的jetty starter容器--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> </dependency>
在嵌入式servlet容器启动的时候需要先配置一个servlet类继承HttpServlet并且实现get和post的方法:
package com.example.springbootdemo.servlet;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;/** * @author Think */public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write('hello,MyServlet'); }}
配置好了之后我们才可以定制自己想要定制的规则springboot1X和springboot2X定制之间会有所差异:2X
/** * 配置嵌入式的servlet容器的相关规则 * @return */ @Bean public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() { return new WebServerFactoryCustomizer<ConfigurableWebServerFactory >() { @Override public void customize(ConfigurableWebServerFactory factory) { //设置服务器启动的端口号为8090factory.setPort(8090); } }; }
1X
@Beanpublic EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer(){ return new EmbeddedServletContainerCustomizer() { @Override public void customize(ConfigurableEmbeddedServletContainer container) { //设置服务器启动的端口号为8090 container.setPort(8090); } };}
配置好之后之间重启一下服务器。在这里给大家展示一下我切换Jetty的运行结果:
当出现类似红色方框的字体的时候,说明就配置成功了。如果你想了解更多的底层源码,你可以到一些学习的网站了解更多比如哔哩哔哩、掘金、Stack Overflow…等。springboot会随着时代的发展而不断的更新,所以如果版本更新了,这里就可能不是你想要的答案了,那么你需要再继续去寻找合理的答案。只要不放弃,你想要的答案总是能找到的。
到此这篇关于springboot2.3.1替换为其他的嵌入式servlet容器的详细方法的文章就介绍到这了,更多相关springboot嵌入式servlet容器内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!
相关文章:
