SpringBoot中启用和测试HTTP/2的几种方法

 更新时间:2025年10月22日 09:16:15   作者:学亮编程手记  
HTTP/2即超文本传输协议第二版,使用于万维网,HTTP/2主要基于SPDY协议,通过对HTTP头字段进行数据压缩、对数据传输采用多路复用和增加服务端推送等举措,本文给大家介绍了SpringBoot中启用和测试HTTP/2的几种方法,需要的朋友可以参考下

前置条件

在开始之前,需要注意:

  • JDK 版本:需要 JDK 9+(推荐 JDK 11 或 17)
  • SSL 证书:HTTP/2 在浏览器中需要 HTTPS,所以需要 SSL 证书

方法一:使用内置 Undertow 服务器(推荐)

Undertow 原生支持 HTTP/2,配置简单,性能优秀。

1. 添加依赖

<!-- pom.xml -->
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <!-- 排除默认的 Tomcat -->
            <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>
</dependencies>

2. 生成 SSL 证书

首先创建一个自签名证书(用于测试):

# 在项目根目录执行
keytool -genkey -alias spring-boot-http2 -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650

# 输入信息(测试时都可以用默认值):
# 密码:password
# 姓名:localhost

3. 配置 application.yml

# application.yml
server:
  port: 8443
  ssl:
    key-store: classpath:keystore.p12
    key-store-password: password
    key-store-type: PKCS12
    key-alias: spring-boot-http2
  # HTTP/2 配置
  http2:
    enabled: true
  # Undertow 特定配置
  undertow:
    threads:
      worker: 64
      io: 4

4. 创建测试 Controller

// Http2DemoController.java
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.stream.LongStream;

@RestController
@RequestMapping("/api")
public class Http2DemoController {
    
    // 普通接口
    @GetMapping("/hello")
    public Map<String, String> hello() {
        return Map.of(
            "message", "Hello HTTP/2!",
            "timestamp", new Date().toString(),
            "protocol", "HTTP/2 with Undertow"
        );
    }
    
    // 模拟大量数据返回,展示 HTTP/2 的多路复用优势
    @GetMapping("/large-data")
    public Map<String, Object> getLargeData() {
        List<Map<String, Object>> data = new ArrayList<>();
        
        for (int i = 0; i < 1000; i++) {
            data.add(Map.of(
                "id", i,
                "name", "Item " + i,
                "value", Math.random() * 1000,
                "timestamp", System.currentTimeMillis() + i
            ));
        }
        
        return Map.of(
            "items", data,
            "total", data.size(),
            "server", "Undertow with HTTP/2"
        );
    }
    
    // 计算密集型任务
    @GetMapping("/calculate")
    public Map<String, Object> calculate() {
        long startTime = System.currentTimeMillis();
        
        // 模拟计算任务
        long sum = LongStream.range(0, 10_000_000)
                .parallel()
                .sum();
        
        long endTime = System.currentTimeMillis();
        
        return Map.of(
            "result", sum,
            "calculationTime", endTime - startTime + "ms",
            "protocol", "HTTP/2"
        );
    }
}

5. 创建主应用类

// SpringBootHttp2Application.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import io.undertow.UndertowOptions;

@SpringBootApplication
public class SpringBootHttp2Application {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootHttp2Application.class, args);
    }
    
    @Bean
    public UndertowServletWebServerFactory undertowServletWebServerFactory() {
        UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory();
        
        factory.addBuilderCustomizers(builder -> {
            // 启用 HTTP/2
            builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true);
            // 其他优化配置
            builder.setServerOption(UndertowOptions.ALWAYS_SET_KEEP_ALIVE, false);
            builder.setServerOption(UndertowOptions.ALWAYS_SET_DATE, true);
        });
        
        return factory;
    }
}

方法二:使用 Tomcat(需要 ALPN)

Tomcat 9+ 也支持 HTTP/2,但配置稍复杂。

1. 依赖配置(使用 Tomcat)

<!-- pom.xml -->
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- 对于 JDK 9+,需要包含 tomcat-embed-core -->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-core</artifactId>
    </dependency>
</dependencies>

2. Tomcat 配置

# application.yml
server:
  port: 8443
  ssl:
    key-store: classpath:keystore.p12
    key-store-password: password
    key-store-type: PKCS12
    key-alias: spring-boot-http2
  http2:
    enabled: true
  # Tomcat 特定配置
  tomcat:
    max-threads: 200
    min-spare-threads: 10

测试 HTTP/2

1. 启动应用

启动 Spring Boot 应用后,你应该看到类似日志:

Tomcat started on port(s): 8443 (https) with context path ''
// 或
Undertow started on port(s): 8443 (https) with context path ''

2. 使用 curl 测试

# 测试 HTTP/2
curl -k -I --http2 https://localhost:8443/api/hello

# 正常请求
curl -k --http2 https://localhost:8443/api/hello

3. 浏览器测试

  1. 访问 https://localhost:8443/api/hello
  2. 由于是自签名证书,浏览器会显示不安全警告,选择"继续前往"
  3. 打开开发者工具 → Network 标签
  4. 刷新页面,在 Protocol 列应该看到 h2(HTTP/2)

4. 创建测试页面展示多路复用优势

// 添加这个 Controller 来演示多请求并发
@Controller
class DemoPageController {
    
    @GetMapping("/")
    public String index() {
        return "index";
    }
}

在 src/main/resources/templates/index.html

<!DOCTYPE html>
<html>
<head>
    <title>HTTP/2 Demo</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1>Spring Boot HTTP/2 演示</h1>
    
    <button onclick="testSequential()">顺序请求测试 (模拟 HTTP/1.1)</button>
    <button onclick="testParallel()">并行请求测试 (HTTP/2 多路复用)</button>
    
    <div id="result"></div>
    
    <script>
        async function testSequential() {
            const start = Date.now();
            const result = $('#result');
            result.html('测试中...');
            
            // 顺序请求
            for (let i = 0; i < 10; i++) {
                await fetch('/api/calculate')
                    .then(r => r.json());
            }
            
            const duration = Date.now() - start;
            result.html(`顺序请求完成: ${duration}ms`);
        }
        
        function testParallel() {
            const start = Date.now();
            const result = $('#result');
            result.html('测试中...');
            
            // 并行请求
            const promises = [];
            for (let i = 0; i < 10; i++) {
                promises.push(fetch('/api/calculate').then(r => r.json()));
            }
            
            Promise.all(promises).then(() => {
                const duration = Date.now() - start;
                result.html(`并行请求完成: ${duration}ms (HTTP/2 多路复用优势)`);
            });
        }
    </script>
</body>
</html>

完整配置示例(生产建议)

对于生产环境,建议使用如下配置:

# application-prod.yml
server:
  port: 443
  ssl:
    key-store: /etc/ssl/certs/keystore.p12
    key-store-password: ${KEYSTORE_PASSWORD}
    key-store-type: PKCS12
    key-alias: my-production-cert
  http2:
    enabled: true
  compression:
    enabled: true
    mime-types: text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json
    min-response-size: 1024
  servlet:
    session:
      timeout: 30m

# Undertow 生产配置
undertow:
  threads:
    worker: 100  # 根据 CPU 核心数调整
    io: 8        # 通常为核心数

# 日志配置
logging:
  level:
    org.springframework: INFO
    io.undertow: WARN

总结

  1. 推荐使用 Undertow:配置简单,性能优秀,原生支持 HTTP/2
  2. 必须配置 SSL:HTTP/2 在浏览器中需要 HTTPS
  3. 多路复用优势:在需要大量并发请求的场景下,HTTP/2 性能提升明显
  4. 向后兼容:HTTP/2 不改变 HTTP 语义,现有代码无需修改

这个示例展示了如何在 Spring Boot 中启用和测试 HTTP/2,你可以直接运行来体验 HTTP/2 的性能优势。

以上就是SpringBoot中启用和测试HTTP/2代码示例的几种方法的详细内容,更多关于SpringBoot启用和测试HTTP/2代码的资料请关注脚本之家其它相关文章!

相关文章

  • Dubbo3和Spring Boot整合过程源码解析

    Dubbo3和Spring Boot整合过程源码解析

    Dubbo首先是提供了一个单独的模块来和Spring Boot做整合,利用 Spring Boot自动装配的功能,配置了一堆自动装配的组件,本文介绍Dubbo3和Spring Boot整合过程,需要的朋友一起看看吧
    2023-08-08
  • JDK多版本管理工具安装和使用详细教程

    JDK多版本管理工具安装和使用详细教程

    随着软件开发环境的日益复杂,多版本Java开发工具包(JDK)管理变得尤为重要,下面这篇文章主要介绍了JDK多版本管理工具安装和使用的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2025-09-09
  • SpringBoot 注解 @AutoConfiguration 在 2.7 版本中被新增的使用方法详解

    SpringBoot 注解 @AutoConfiguration 在 2.7 版本中被新增的使用方法详解

    这篇文章主要介绍了SpringBoot 注解 @AutoConfiguration 在 2.7 版本中被新增(使用方法),本文给大家介绍的非常详细,需要的朋友可以参考下
    2024-09-09
  • 在Spring Boot中如何使用Cookies详析

    在Spring Boot中如何使用Cookies详析

    这篇文章主要给大家介绍了关于在Spring Boot中如何使用Cookies的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者使用Spring Boot具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-11-11
  • SpringBoot重写addResourceHandlers映射文件路径方式

    SpringBoot重写addResourceHandlers映射文件路径方式

    这篇文章主要介绍了SpringBoot重写addResourceHandlers映射文件路径方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-02-02
  • Java中常用的类型转换(推荐)

    Java中常用的类型转换(推荐)

    这篇文章主要介绍了Java中常用的类型转换(推荐)的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
    2016-06-06
  • 解决Spring Boot应用打包后文件访问问题

    解决Spring Boot应用打包后文件访问问题

    在Spring Boot项目的开发过程中,一个常见的挑战是如何有效地访问和操作资源文件,本文就来介绍一下解决Spring Boot应用打包后文件访问问题,感兴趣的可以了解一下
    2024-01-01
  • javamail 发送邮件的实例代码分享

    javamail 发送邮件的实例代码分享

    今天学习了一下JavaMail,javamail发送邮件确实是一个比较麻烦的问题。为了以后使用方便,自己写了段代码,打成jar包,以方便以后使用
    2013-08-08
  • Spring整合Mybatis使用<context:property-placeholder>时的坑

    Spring整合Mybatis使用<context:property-placeholder>时的坑

    这篇文章主要介绍了Spring整合Mybatis使用<context:property-placeholder>时的坑 的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
    2016-06-06
  • Mybatisplus主键生成策略算法解析

    Mybatisplus主键生成策略算法解析

    这篇文章主要介绍了Mybatisplus主键生成策略算法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11

最新评论