主题
🔗 gRPC 协议
REST API 是 JSON 聊天,gRPC 是 Protobuf 电报——更快、更小、更结构化
gRPC 是什么
Google 开源的高性能 RPC 框架,基于 HTTP/2 + Protocol Buffers。
| 对比 | REST API | gRPC |
|---|---|---|
| 协议 | HTTP/1.1 | HTTP/2 |
| 数据格式 | JSON(文本) | Protobuf(二进制) |
| 接口定义 | 口头约定 / OpenAPI | .proto 文件强制 |
| 流式通信 | 不支持 | 原生支持 |
| 代码生成 | 手动写 | 自动生成客户端/服务端 |
| 浏览器 | 原生支持 | 需 grpc-web |
| 性能 | 一般 | 高(二进制+HTTP/2 多路复用) |
ProtoBuf:定义接口
protobuf
// model.proto
syntax = "proto3";
package ai;
// 推理请求
message InferenceRequest {
string model_name = 1;
string prompt = 2;
int32 max_tokens = 3;
float temperature = 4;
}
// 推理响应
message InferenceResponse {
string text = 1;
int32 tokens_used = 2;
float inference_time_ms = 3;
}
// 推理服务
service InferenceService {
// 单次推理
rpc Infer(InferenceRequest) returns (InferenceResponse);
// 流式推理(服务器持续推送结果)
rpc StreamInfer(InferenceRequest) returns (stream InferenceResponse);
}Python 实现 gRPC 推理服务
python
# pip install grpcio grpcio-tools
# 编译 proto: python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. model.proto
import grpc
from concurrent import futures
import model_pb2
import model_pb2_grpc
class InferenceService(model_pb2_grpc.InferenceServiceServicer):
def Infer(self, request, context):
# 调用推理引擎
result = run_inference(
model=request.model_name,
prompt=request.prompt,
max_tokens=request.max_tokens
)
return model_pb2.InferenceResponse(
text=result['text'],
tokens_used=result['tokens'],
inference_time_ms=result['time_ms']
)
def StreamInfer(self, request, context):
# 流式推理——每个 token 推一次
for token in stream_inference(request.prompt):
yield model_pb2.InferenceResponse(
text=token,
tokens_used=1,
inference_time_ms=5.0
)
# 启动服务
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
model_pb2_grpc.add_InferenceServiceServicer_to_server(
InferenceService(), server
)
server.add_insecure_port('[::]:50051')
server.start()
server.wait_for_termination()gRPC 的四种通信模式
| 模式 | 说明 | .proto 定义 |
|---|---|---|
| 一元 RPC | 发一个请求等一个响应 | rpc Method(Req) returns (Res) |
| 服务端流式 | 请求一个,响应一串 | rpc Method(Req) returns (stream Res) |
| 客户端流式 | 请求一串,响应一个 | rpc Method(stream Req) returns (Res) |
| 双向流式 | 双方同时流式 | rpc Method(stream Req) returns (stream Res) |
AI 推理场景最常用:服务端流式——用户发一个 prompt,模型逐 token 推回来。
gRPC 的 HTTP/2 优势
HTTP/1.1(REST API 传统做法):
每个请求一个 TCP 连接(或 Keep-Alive 复用,但队头阻塞严重)
HTTP/2(gRPC 底层):
一个 TCP 连接上有多个 stream,互不阻塞
┌─────────────────────────────┐
│ TCP Connection │
│ ├─ Stream 1: 推理请求A │
│ ├─ Stream 2: 推理请求B │
│ ├─ Stream 3: 健康检查 │
│ └─ Stream 4: 推理请求C │
└─────────────────────────────┘什么时候用 gRPC vs REST
| 场景 | 选型 |
|---|---|
| 对外公开 API | REST(兼容性好,curl 就能调) |
| 内部微服务通信 | gRPC(高性能、强类型) |
| AI 推理流式输出 | gRPC 服务端流(比 SSE 更高效) |
| 多语言互通 | gRPC(自动生成 12 种语言客户端) |
| 浏览器前端调用 | REST 或 grpc-web |
| 低带宽环境(IoT) | gRPC(二进制 Protobuf 比 JSON 小很多) |
gRPC + nginx 代理
nginx 1.13.10+ 支持 gRPC 代理:
nginx
server {
listen 443 ssl http2;
server_name grpc.example.com;
location /ai.InferenceService {
grpc_pass grpc://127.0.0.1:50051;
}
}注意:grpc_pass 不是 proxy_pass,底层是 HTTP/2。
🎯 本章要点
- gRPC = HTTP/2 + ProtoBuf,比 REST JSON 更快更小
- .proto 定义接口,自动生成客户端/服务端代码
- 四种模式:一元、服务端流(AI 推理标配)、客户端流、双向流
- 内部微服务优先 gRPC,对外 API 优先 REST
- nginx 用
grpc_pass代理 gRPC,不是proxy_pass
加载练习题中...