第23章:实战三 —— 微服务网关
本章目标
用 gRPC Gateway 构建 API 网关,整合多个下游微服务
架构
浏览器/REST客户端
│
▼
┌─────────────────┐
│ API Gateway │ (HTTP :8080)
│ (gRPC Gateway) │
└───┬─────┬──────┘
│ │
▼ ▼
┌───────┐ ┌───────┐
│ Auth │ │ Order │ (gRPC :50051, :50052)
│Service│ │Service│
└───────┘ └───────┘Gateway 核心代码
go
func main() {
ctx := context.Background()
mux := runtime.NewServeMux()
opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
// 注册多个下游服务
pbAuth.RegisterAuthServiceHandlerFromEndpoint(ctx, mux, "localhost:50051", opts)
pbOrder.RegisterOrderServiceHandlerFromEndpoint(ctx, mux, "localhost:50052", opts)
// 认证中间件
http.ListenAndServe(":8080", authMiddleware(mux))
}关键功能
- 统一入口:一个 :8080 端口整合多个 gRPC 服务
- JWT 透传:从 HTTP Header 提取 JWT → 注入 gRPC Metadata
- 请求聚合:一个 REST 接口聚合多个 RPC 调用
练习题
- 实现 API Gateway 整合两个 gRPC 服务。
- 添加请求限流中间件。