SpringBoot自动配置,切换内置Web服务器

2023年 7月 22日 93.8k 0

前言

之前面试有被问到过一个问题:SpringBoot可以同时处理多少请求?我们怎么更改它默认的Web服务器?

简介

SpringBoot的内置环境默认使用Tomcat作为内置服务器,其实SpringBoot提供了四种内置服务器供我们选择,分别是Jetty、Netty、Tomcat、Undertow

默认服务器

1.默认服务器

SpringBoot项目启动,默认以Tomcat服务器启动
image.png

2.其他配置的服务器

内置服务器配置,在SpringFramework-web包中可以查看到
image.png

3.如何切换内置服务器

Maven坐标中排除Tomcat依赖,引入其他内置服务器依赖

image.png

SpringBoot处理请求

由于SpringBoot默认使用的是Tomcat服务器,那么SpringBoot可以同时处理多少请求,也就是Tomcat可以处理多少请求
其实在Spring包中,都有定义线程请求数量的阈值,以及我们可以通过配置文件去更改这些参数配置,在spring-boot-autoconfigure包下的spring-configuration-metadata.json文件中有定义关于Tomcat的参数配置

最大连接数
{
  "name": "server.tomcat.max-connections",
  "type": "java.lang.Integer",
  "description": "Maximum number of connections that the server accepts and processes at any given time. Once the limit has been reached, the operating system may still accept connections based on the "acceptCount" property.",
  "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties$Tomcat",
  "defaultValue": 8192
},
最大等待数
{
  "name": "server.tomcat.accept-count",
  "type": "java.lang.Integer",
  "description": "Maximum queue length for incoming connection requests when all possible request processing threads are in use.",
  "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties$Tomcat",
  "defaultValue": 100
},
最少线程数
{
  "name": "server.tomcat.threads.min-spare",
  "type": "java.lang.Integer",
  "description": "Minimum amount of worker threads.",
  "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties$Tomcat$Threads",
  "defaultValue": 10
},
最多线程数
{
  "name": "server.tomcat.threads.max",
  "type": "java.lang.Integer",
  "description": "Maximum amount of worker threads.",
  "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties$Tomcat$Threads",
  "defaultValue": 200
},

可以通过application.yml去更改Tomcat的参数配置

server:
  port: 8081
  tomcat:
    threads:
      min-spare: 10 #最少线程数
      max: 200 #最多线程数
    max-connections: 8192 #最大连接数
    accept-count: 100 #最大等待数
# SpringBoot可以同时处理多少请求:SpringBoot内嵌Tomcat,其实也就是Tomcat能处理多少请求
# spring-configuration-metadata.json中有设置Tomcat的系列参数
spring:
  application:
    name: spring-tomcat
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/study?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT
    username: root
    password: root
  jpa:
    show-sql: true #是否显示SQL语句

总结

SpringBoot可以同时处理大量的请求,有它自己的默认配置参数,我们可以通过调试配置来增加并发能力,但是还是需要视具体业务场景具体分析,以选择不同的内置服务器和参数配置

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论