java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot启用和测试HTTP/2

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

作者:学亮编程手记

HTTP/2即超文本传输协议第二版,使用于万维网,HTTP/2主要基于SPDY协议,通过对HTTP头字段进行数据压缩、对数据传输采用多路复用和增加服务端推送等举措,本文给大家介绍了SpringBoot中启用和测试HTTP/2的几种方法,需要的朋友可以参考下

前置条件

在开始之前,需要注意:

方法一:使用内置 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代码的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文