首页  >  文章  >  Java  >  提高 Spring Boot 应用程序的性能 - 第一部分

提高 Spring Boot 应用程序的性能 - 第一部分

王林
王林原创
2024-08-22 12:33:43618浏览

Melhorando o desempenho de aplicações Spring Boot - Parte I

启动 Spring Boot 应用程序时,我们通常使用启动器提供的默认设置,这对于大多数情况来说已经足够了。但是,如果我们需要性能,则可以进行具体调整,如本文第一部分所示。

Tomcat 替换为另一个 servlet 容器

使用

Spring MVCwebRESTFul 应用程序,通常添加 spring-boot-starter-web 依赖,默认使用 Tomcat 作为网络服务器。然而,还有更有趣的替代方案,例如 Undertow,它是一个高性能 web 服务器,具有异步和非阻塞架构,允许您处理大量数据高效的同时连接,使其适合高性能应用。我们并不是说Tomcat不好,但我们可以给Undertow一个机会。

Spring中添加Undertow

为了让我们使用 Undertow 作为 web 服务器,我们需要忽略 spring-boot-starter-web 已经添加的 spring-boot-starter-tomcat 依赖项然后添加 spring-boot-starter-undertow。

使用 pom.xml:

<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>
            </exclusions>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-undertow</artifactId>
    </dependency>
</dependencies>

使用build.gradle:

dependencies {
    implementation('org.springframework.boot:spring-boot-starter-web') {
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
    }
    implementation 'org.springframework.boot:spring-boot-starter-undertow'
}

配置潜流

通过 application.properties 或 application.yml,我们可以配置我们希望服务器使用多少个 IO 线程 和多少个 工作线程

使用 application.yml

server:
  undertow:
    threads:
      io: 4
      worker: 64

使用 application.properties

server.undertow.threads.io=4
server.undertow.threads.worker=64

I/O 线程 执行非阻塞操作,并且永远不应该执行阻塞操作,因为它们负责侦听到达应用程序的连接,然后将它们发送到处理队列。常见值为每个 CPU 核心两个 I/O 线程

工作线程执行阻塞操作,例如由I/O 线程发送到处理队列的Servlet请求。理想值取决于工作负载,但通常建议每个 CPU 核心配置 10 个左右的线程。

有关更详细的信息和更多可以探索的选项,只需转到 Undertow 文档。

压缩 HTTP 响应

数据压缩是一项旨在减少 HTTP 响应正文大小的功能,从而可以通过减少通过网络传输的数据量来提高应用程序的性能。

在 Spring Boot 中配置数据压缩是一项简单的任务,因为它支持此功能。

使用 application.yml

server:
  compression:
    enabled: true
    mime-types: text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json
    min-response-size: 1024

使用 application.properties

server.compression.enabled=true
server.compression.mime-types=text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json
server.compression.min-response-size=1024

server.compression.enabled:启用/禁用压缩。
server.compression.mime-types:应压缩的 MIME 类型列表。
server.compression.min-response-size:执行压缩所需的“Content-Length”的最小大小。

至此,我们结束了文章的第一部分。在下一部分中,我们将详细了解 Hikari、JPA 和 Hibernate,并学习如何配置它们,以进一步提高 Spring Boot 应用程序的性能。

以上是提高 Spring Boot 应用程序的性能 - 第一部分的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn