Web容器选择配置
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<dependency>
</dependencies>
首先一定要明确SpringBoot中在spring-boot-starter-web当中是自带Web容器默认tomcat,因为tomcat是开源免费的
Web容器不使用tomcat配置
<dependencies>
<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>
</dependencies>
这样就去除了tomcat,依赖项中就不会出现tomcat,当然也不会有tomcat启动
使用其他的Web容器配置
例如我不想使用tomcat,而想使用jetty,在pom.xml文件中加入jetty依赖
<dependencies>
<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-jetty</artifactId>
</dependency>
</dependencies>
Tomcat的基本配置
在application.properties中配置
#spring.main.web-application-type=none 不启动web容器 禁止web容器
#server.port=8888 设置端口号
#server.port=-1 关闭所有http端口
#server.port=0 设置随机端口
#开启gzip压缩 Content-Encoding: gzip
server.compression.enabled=true 开启gzip压缩
#server.compression.mime-types 压缩设置默认中没有的格式
#server.compression.min-response-size 超过最低限度就去压缩
设置随机端口
server.port=0 设置随机端口
设置随机端口之后我们想要获得端口号,就必须要设置监听类来获得
@Component//注入到Spring中
public class MyApplicationListener implements ApplicationListener<WebServerInitializedEvent> {
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
//获取web容器,得到随机端口
System.out.println("event.getWebServer().getPort() = " + event.getWebServer().getPort());
}
}
开启gzip压缩
server.compression.enabled=true
我们写一个测试类:
@RestController
public class HelloController {
@GetMapping("/hello")
public List<String> getusers(){
List<String> users = new ArrayList<String>();
for (int i = 0;i <= 10000;i++){
users.add("dong:"+i);
}
return users;
}
}
没有经过gzip压缩的:
经过压缩的: