我们以Main方式启动springboot应用,默认是使用springboot内置容器tomcat启动的,springboot支持的容器除了tomcat还有jetty和undertow等等,接下来我们就通过编码来分别实现springboot2.x基于不同的容器启动。
springboot&tomcat
springboot的默认启动方式是使用内置的tomcat容器,只要pom中引入了spring-boot-starter-web依赖,应用就可以直接启动。
1.引入依赖
除了最基础的依赖spring-boot-starter,还需要引入spring-boot-starter-web:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.编写测试代码
@RestController
@Slf4j
public class IndexController {
@GetMapping("/hello")
public String hello() {
log.info("print log ,string={}","hello");
return "hello";
}
}
3.运行&测试
运行应用启动类,浏览器输入http://localhost:8080/hello:
应用正常启动并且能够接收请求,使用内嵌tomcat启动springboot成功。
springboot&jetty
jetty是一款轻量级的web容器,在国内市场也占有一定的份额。Jetty 是一个开源的servlet容器,它为基于Java的web容器,例如JSP和servlet提供运行环境。Jetty是使用Java语言编写的,它的API以一组JAR包的形式发布。开发人员可以将Jetty容器实例化成一个对象,可以迅速为一些独立运行(stand-alone)的Java应用提供网络和web连接。
1.引入依赖
引入spring-boot-starter-web要排掉内嵌tomcat,另外引入spring-boot-starter-jetty依赖:
<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>
<!-- jetty -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
2.运行&测试
运行应用启动类:
浏览器输入http://localhost:8080/hello:
应用正常启动并且能够接收请求,使用jetty启动springboot成功。
springboot&undertow
Undertow 是红帽公司开发的一款基于 NIO 的高性能 Web 嵌入式服务器,也是一款springboot推荐使用的轻量级web容器。
1.引入依赖
引入spring-boot-starter-undertow,并排掉spring-boot-starter-web的内嵌tomcat:
<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>
<!-- undertow -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
2.运行&测试
运行应用启动类:
浏览器输入http://localhost:8080/hello:
应用正常启动并且能够接收请求,使用undertow启动springboot成功。
总结
一般springboot推荐使用内嵌tomcat,jetty和undertow启动,当然也可部署到外部tomcat容器启动,默认是使用内嵌tomcat启动,使用的时候只需要引入spring-boot-starter-web依赖就会把spring-boot-starter-tomcat带进来:
一般情况下不需要关注,具体使用哪种容器启动还需要根据个人喜好和满足特定的场景也抉择。
本文分享自 PersistentCoder 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!