# http2-running **Repository Path**: coderwing/http2-running ## Basic Information - **Project Name**: http2-running - **Description**: http2学习 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-11-02 - **Last Updated**: 2025-11-08 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # HTTP/2 + WebFlux 学习项目 ## 📚 项目简介 这是一个完整的HTTP/2 + Spring WebFlux学习项目,通过实现一个用户管理系统来演示HTTP/2的各种特性和使用方法。 ### 🎯 学习目标 - 深入理解HTTP/2协议的核心特性 - 掌握Spring WebFlux响应式编程 - 学会如何在生产项目中使用HTTP/2 - 了解HTTP/2与HTTP/1.1的性能差异 ## 🚀 HTTP/2 核心特性 ### 1. 多路复用 (Multiplexing) **原理:** HTTP/2在单个TCP连接上可以并发处理多个请求和响应,每个请求响应对称为一个"流"(Stream)。 **优势:** - 消除了HTTP/1.1的队头阻塞问题 - 减少TCP连接数量,降低服务器负载 - 提高带宽利用率 **示例代码:** ```java // 在单个连接上并发处理多个请求 Mono.zip( getUserInfo(), getUserProfile(), getUserSettings(), getNotifications() ).subscribe(); ``` **演示接口:** `GET /api/demo/multiplexing` ### 2. 头部压缩 (Header Compression - HPACK) **原理:** HTTP/2使用HPACK算法压缩HTTP头部,维护头部字段表,避免重复传输。 **优势:** - 减少约67%的头部传输量 - 降低延迟,提高传输效率 - 特别适合移动网络环境 **对比:** ``` HTTP/1.1: 每次请求完整传输所有头部 原始大小: ~800 bytes HTTP/2: 使用HPACK压缩头部 压缩后: ~250 bytes (节省约70%) ``` **演示接口:** `GET /api/demo/header-compression` ### 3. 服务器推送 (Server Push) **原理:** 服务器可以主动向客户端推送资源,而不需要客户端明确请求。 **应用场景:** - 推送CSS、JavaScript等关联资源 - 预加载用户可能需要的数据 - 推送实时通知 **示例:** ```java // 客户端请求index.html时,服务器主动推送相关资源 GET /index.html → Server Push: style.css → Server Push: app.js → Server Push: logo.png ``` **演示接口:** `GET /api/demo/server-push` ### 4. 流优先级 (Stream Prioritization) **原理:** 可以为HTTP/2流设置优先级和权重,优先传输重要资源。 **优先级设置:** - HIGH (256): 关键CSS、首屏资源 - MEDIUM (128): JavaScript、API数据 - LOW (64): 图片、视频等非关键资源 **演示接口:** `GET /api/demo/stream-priority` ### 5. 二进制帧 (Binary Framing) **原理:** HTTP/2使用二进制格式传输数据,而不是HTTP/1.1的文本格式。 **优势:** - 更高效的解析和处理 - 减少错误和歧义 - 更容易实现多路复用 - 更小的传输体积 **演示接口:** `GET /api/demo/binary-framing` ### 6. 流控制 (Flow Control) **原理:** 提供连接级别和流级别的流控制机制,防止快速发送方压垮慢速接收方。 **配置参数:** ```yaml http2: client: initial-window-size: 1048576 # 1MB max-frame-size: 16384 # 16KB max-header-list-size: 8192 # 8KB ``` **演示接口:** `GET /api/demo/flow-control` ## 🏗️ 项目架构 ``` http2-webflux-demo/ ├── src/main/java/com/study/http2/ │ ├── Http2WebfluxDemoApplication.java # 主应用类 │ ├── config/ │ │ ├── Http2Configuration.java # HTTP/2配置 │ │ └── R2dbcConfiguration.java # 数据库配置 │ ├── entity/ │ │ ├── User.java # 用户实体 │ │ ├── UserLoginLog.java # 登录日志 │ │ └── UserActivity.java # 用户活动 │ ├── repository/ │ │ ├── UserRepository.java # 用户Repository │ │ ├── UserLoginLogRepository.java # 登录日志Repository │ │ └── UserActivityRepository.java # 活动Repository │ ├── service/ │ │ └── UserService.java # 用户服务 │ ├── controller/ │ │ ├── UserController.java # 用户Controller │ │ └── HomeController.java # 首页Controller │ ├── client/ │ │ └── Http2Client.java # HTTP/2客户端封装 │ ├── demo/ │ │ └── Http2FeaturesController.java # HTTP/2特性演示 │ └── dto/ │ ├── UserDTO.java # 用户DTO │ └── ApiResponse.java # 统一响应格式 ├── src/main/resources/ │ ├── application.yml # 主配置文件 │ ├── application-dev.yml # 开发环境配置 │ ├── schema.sql # 数据库结构 │ ├── data.sql # 测试数据 │ └── keystore.p12 # SSL证书(需要生成) └── pom.xml # Maven配置 ``` ## 🛠️ 技术栈 - **Spring Boot 3.2.0** - 应用框架 - **Spring WebFlux** - 响应式Web框架 - **Project Reactor** - 响应式编程库 - **Reactor Netty** - 异步网络库(支持HTTP/2) - **Spring Data R2DBC** - 响应式数据库访问 - **MySQL** - 关系型数据库 - **R2DBC MySQL** - MySQL响应式驱动 - **Lombok** - 简化Java代码 ## 📦 快速开始 ### 1. 环境要求 - JDK 17+ - Maven 3.6+ - MySQL 8.0+ - 支持HTTP/2的浏览器或工具(Chrome、Firefox、curl等) ### 2. 数据库准备 ```sql -- 创建数据库 CREATE DATABASE http2_demo CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; -- 修改配置文件中的数据库连接信息 spring: r2dbc: url: r2dbc:mysql://localhost:3306/http2_demo username: root password: your_password ``` ### 3. 生成SSL证书 HTTP/2需要TLS支持,生成自签名证书: ```bash keytool -genkeypair -alias http2demo \ -keyalg RSA -keysize 2048 -storetype PKCS12 \ -keystore src/main/resources/keystore.p12 \ -validity 3650 \ -dname "CN=localhost, OU=Study, O=HTTP2Demo, L=Beijing, ST=Beijing, C=CN" \ -storepass changeit ``` ### 4. 编译运行 ```bash # 编译项目 mvn clean package # 运行项目(HTTPS模式) java -jar target/http2-webflux-demo-1.0.0.jar # 或运行开发模式(HTTP模式,无需SSL) java -jar target/http2-webflux-demo-1.0.0.jar --spring.profiles.active=dev ``` ### 5. 访问应用 - **HTTPS模式:** https://localhost:8443 - **开发模式:** http://localhost:8080 - **API文档:** https://localhost:8443/api/docs ## 📝 API接口说明 ### 用户管理接口 | 方法 | 路径 | 说明 | |------|------|------| | GET | /api/users | 获取所有用户 | | GET | /api/users/{id} | 获取指定用户 | | POST | /api/users | 创建用户 | | PUT | /api/users/{id} | 更新用户 | | DELETE | /api/users/{id} | 删除用户 | | GET | /api/users/active | 获取活跃用户 | | POST | /api/users/{id}/login | 记录用户登录 | | GET | /api/users/{id}/login-logs | 获取登录日志 | | GET | /api/users/{id}/activities | 获取用户活动 | | GET | /api/users/{id}/statistics | 获取用户统计 | ### HTTP/2特性演示接口 | 方法 | 路径 | 说明 | |------|------|------| | GET | /api/demo/multiplexing | 演示多路复用 | | GET | /api/demo/header-compression | 演示头部压缩 | | GET | /api/demo/server-push | 演示服务器推送 | | GET | /api/demo/stream-priority | 演示流优先级 | | GET | /api/demo/binary-framing | 演示二进制帧 | | GET | /api/demo/flow-control | 演示流控制 | | GET | /api/demo/sse | 演示服务器发送事件 | | GET | /api/demo/concurrent-streams | 演示并发流 | | GET | /api/demo/performance-comparison | 性能对比 | ## 🧪 测试示例 ### 使用curl测试HTTP/2 ```bash # 查看所有用户(HTTP/2) curl -k --http2 https://localhost:8443/api/users # 创建用户 curl -k --http2 -X POST https://localhost:8443/api/users \ -H "Content-Type: application/json" \ -d '{ "username": "testuser", "email": "test@example.com", "password": "password123", "fullName": "测试用户", "age": 25 }' # 获取用户详情 curl -k --http2 https://localhost:8443/api/users/1 # 演示多路复用 curl -k --http2 https://localhost:8443/api/demo/multiplexing # 演示服务器发送事件 curl -k --http2 -N https://localhost:8443/api/demo/sse ``` ### 使用浏览器测试 在Chrome浏览器中: 1. 访问 https://localhost:8443(忽略证书警告) 2. 打开开发者工具(F12) 3. 切换到Network标签 4. 查看Protocol列,应显示为"h2"(HTTP/2) ### 性能对比测试 ```bash # HTTP/1.1 性能测试 ab -n 1000 -c 10 http://localhost:8080/api/users # HTTP/2 性能测试(需要支持HTTP/2的工具) h2load -n 1000 -c 10 https://localhost:8443/api/users ``` ## 📊 HTTP/2 vs HTTP/1.1 性能对比 ### 测试场景:并发请求10个资源 | 指标 | HTTP/1.1 | HTTP/2 | 提升 | |------|----------|--------|------| | 连接数 | 6个 | 1个 | -83% | | 总耗时 | ~800ms | ~300ms | 62.5% | | 头部大小 | ~8KB | ~2.5KB | 68.75% | | 队头阻塞 | 存在 | 无 | ✓ | ### 实际应用场景性能提升 - **页面加载速度:** 提升30-50% - **API响应时间:** 减少20-40% - **移动网络环境:** 提升50-70% - **多资源并发:** 提升60-80% ## 🔧 在生产项目中使用HTTP/2 ### 1. Nginx配置HTTP/2 ```nginx server { listen 443 ssl http2; server_name your-domain.com; ssl_certificate /path/to/cert.pem; ssl_certificate_key /path/to/key.pem; # HTTP/2推送 http2_push_preload on; location / { proxy_pass http://backend:8080; proxy_http_version 1.1; # 转发HTTP/2头部 proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } ``` ### 2. Spring Boot配置优化 ```yaml server: http2: enabled: true ssl: enabled: true key-store: classpath:keystore.p12 key-store-password: ${SSL_PASSWORD} key-store-type: PKCS12 netty: # 优化连接数 connection-timeout: 2000 # HTTP/2配置 h2c-max-content-length: 0 ``` ### 3. 客户端配置 ```java @Bean public WebClient http2WebClient(ConnectionProvider provider) { HttpClient httpClient = HttpClient.create(provider) .protocol(HttpProtocol.H2, HttpProtocol.HTTP11) .http2Settings(settings -> { settings.maxConcurrentStreams(100L); settings.initialWindowSize(1048576); }); return WebClient.builder() .clientConnector(new ReactorClientHttpConnector(httpClient)) .build(); } ``` ### 4. 最佳实践 #### ✅ 推荐做法 - 启用HTTPS(HTTP/2几乎总是需要TLS) - 合理配置连接池大小 - 使用流优先级优化关键资源加载 - 利用服务器推送预加载资源 - 监控HTTP/2连接和流的使用情况 #### ❌ 避免的做法 - 不要维护过多的HTTP连接 - 避免过大的帧大小配置 - 不要忽略流控制设置 - 避免不必要的服务器推送(可能浪费带宽) ### 5. 监控和调试 ```java // 启用详细日志 logging: level: io.netty: DEBUG reactor.netty: DEBUG // 使用Actuator监控 management: endpoints: web: exposure: include: health,metrics,httptrace ``` ## 🎓 学习路径 ### 初级 1. 了解HTTP/2基本概念 2. 运行本项目,体验HTTP/2特性 3. 对比HTTP/1.1和HTTP/2的差异 ### 中级 1. 深入学习HTTP/2协议规范 2. 掌握Spring WebFlux响应式编程 3. 理解HTTP/2的性能优化原理 ### 高级 1. 学习HTTP/2的底层实现(帧结构、流管理) 2. 优化生产环境HTTP/2配置 3. 研究HTTP/3(QUIC协议) ## 📚 参考资料 ### 官方文档 - [HTTP/2 RFC 7540](https://tools.ietf.org/html/rfc7540) - [HPACK RFC 7541](https://tools.ietf.org/html/rfc7541) - [Spring WebFlux 文档](https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html) - [Reactor Netty 文档](https://projectreactor.io/docs/netty/release/reference/index.html) ### 学习资源 - [HTTP/2 简介](https://developers.google.com/web/fundamentals/performance/http2) - [HTTP/2 性能测试](https://www.httpvshttps.com/) - [WebFlux 教程](https://spring.io/guides/gs/reactive-rest-service/) ## 🤝 贡献指南 欢迎提交Issue和Pull Request! ## 📄 许可证 MIT License ## 👨‍💻 作者 Study - HTTP/2学习项目 ## 🔗 相关链接 - [项目地址](https://github.com/yourusername/http2-webflux-demo) - [问题反馈](https://github.com/yourusername/http2-webflux-demo/issues) --- **Happy Coding! 🎉**