9 -【 SpringBoot 性能优化 】

1 扫包优化

扫包属于启动优化,不属于运行优化

1.1 组件自动扫描带来的问题

使用 @SpringBootApplication 注解,会遍历包下面的子类,会影响性能。

默认情况下,我们会使用 @SpringBootApplication 注解来自动获取应用的配置信息,但这样也会给应用带来一些副作用。

使用这个注解后,会触发 自动配置( auto-configuration )和 组件扫描 ( component scanning ),这跟使用 @Configuration@EnableAutoConfiguration@ComponentScan 三个注解的作用是一样的。这样做给开发带来方便的同时,也会有三方面的影响:

  1. 会导致项目启动时间变长。当启动一个大的应用程序,或将做大量的集成测试启动应用程序时,影响会特别明显。
  2. 会加载一些不需要的多余的实例(beans)。
  3. 会增加 CPU 消耗。

针对以上三个情况,我们可以移除 @SpringBootApplication@ComponentScan 两个注解来禁用组件自动扫描,然后在我们需要的 bean 上进行显式配置:

// 移除 @SpringBootApplication and @ComponentScan, 用 @EnableAutoConfiguration 来替代
// @SpringBootApplication
@ComponentScan(basePackages = "com.snow")
@EnableAutoConfiguration
public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

}

2 SpringBoot JVM 参数调优

JVM 参数调优,属于整体优化

这个根据服务器的内存大小,来设置堆参数。

  • -Xms:设置 Java 堆栈的初始化大小
  • -Xmx:设置最大的 java 堆大小
    实例参数 -XX:+PrintGCDetails -Xmx32M -Xms1M

本地项目调优:
在这里插入图片描述

外部运行调优:

java -server -Xms32m -Xmx32m  -jar springboot_v2.jar

3 将 Servlet 容器变成 Undertow

3.1 步骤

默认情况下,Spring Boot 使用 Tomcat 来作为内嵌的 Servlet 容器。

可以将 Web 服务器切换到 Undertow 来提高应用性能。

Undertow 是一个采用 Java 开发的灵活的高性能 Web 服务器,提供包括阻塞和基于 NIO 的非堵塞机制。Undertow 是红帽公司的开源产品,是 Wildfly 默认的 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>

启动,发现使用的是 Undertow
在这里插入图片描述

3.2 测试

创建线程组
在这里插入图片描述
每次请求 10000 次
在这里插入图片描述

创建 HTTP 请求:
在这里插入图片描述

测试:
在这里插入图片描述

创建聚合报告:
在这里插入图片描述

测试:
点击运行,查看测试报告
在这里插入图片描述
在这里插入图片描述

服务器名称 第一次运行 第二次运行 第三次运行 平均值
Tomcat 4773 5194 5334.7 5100
Undertow 6666 6373 6451 6496
发布了663 篇原创文章 · 获赞 213 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/weixin_42112635/article/details/104878172