`grpcio` 是 Google 开发的 gRPC 框架的 Python 实现,是一个高性能、开源的通用 RPC(远程过程调用)框架

grpcio是 Google 开发的 gRPC 框架的 Python 实现,是一个高性能、开源的通用 RPC(远程过程调用)框架,基于 HTTP/2 协议和 Protocol Buffers(protobuf)序列化格式。其核心优势包括:

高性能:利用 HTTP/2 的多路复用、头部压缩、服务端推送等特性,显著降低延迟与连接开销;
强类型接口:通过.proto文件定义服务契约,自动生成客户端/服务端存根(stub),保障类型安全与 IDE 支持;
多语言支持:跨语言互通(Python/Go/Java/C++/JS 等),天然适合微服务架构;
内置功能丰富:支持双向流式通信、拦截器(interceptors)、认证(TLS/mTLS、JWT)、负载均衡、健康检查、超时与重试等;
异步支持完善:提供async def风格的异步服务端(aio模块)和客户端,适配 asyncio 生态。

安装方式:

pipinstallgrpcio grpcio-tools

典型使用流程:

  1. 编写.proto文件定义 service 和 message;
  2. 使用protoc --python_out=. --grpc_python_out=. xxx.proto生成 Python 代码;
  3. 实现服务端逻辑并启动 gRPC server;
  4. 创建客户端 stub 并发起同步或异步调用。

示例(简略):

# hello_pb2_grpc.py(自动生成)importhello_pb2,hello_pb2_grpcclassGreeterServicer(hello_pb2_grpc.GreeterServicer):defSayHello(self,request,context):returnhello_pb2.HelloReply(message=f'Hello,{request.name}!')# 启动服务端server=grpc.server(futures.ThreadPoolExecutor(max_workers=10))hello_pb2_grpc.add_GreeterServicer_to_server(GreeterServicer(),server)server.add_insecure_port('[::]:50051')server.start()server.wait_for_termination()

⚠️ 注意事项:生产环境建议启用 TLS 加密、合理配置最大消息大小(max_message_length)、启用 Keepalive 参数以维持长连接稳定性。

在 gRPC Python 中实现双向流式通信(Bidirectional Streaming),需定义.proto文件中服务方法的请求和响应类型均为stream,并在服务端和客户端均使用异步迭代器(async for)或同步生成器(for+iter)进行持续收发。以下是完整、可运行的示例:


✅ 步骤 1:定义.proto文件(chat.proto

syntax = "proto3"; package chat; service ChatService { // 双向流:客户端和服务端均可连续发送/接收消息 rpc Chat(stream ChatMessage) returns (stream ChatMessage); } message ChatMessage { string sender = 1; string message = 2; int64 timestamp = 3; }

✅ 步骤 2:生成 Python 代码

python-mgrpc_tools.protoc -I.--python_out=.--grpc_python_out=. chat.proto

生成chat_pb2.pychat_pb2_grpc.py


✅ 步骤 3:服务端实现(支持同步/异步;推荐aio异步方式)

# server.pyimportasyncioimporttimeimportchat_pb2,chat_pb2_grpcclassChatServicer(chat_pb2_grpc.ChatServiceServicer):asyncdefChat(self,request_iterator,context):asyncforrequestinrequest_iterator:# 接收客户端流print(f"[Server] Received from{request.sender}:{request.message}")# 回复(可实时、可延迟、可广播)reply=chat_pb2.ChatMessage(sender="server",message=f"Echo:{request.message}",timestamp=int(time.time()))yieldreply# 发送流式响应asyncdefserve():server=grpc.aio.server()chat_pb2_grpc.add_ChatServiceServicer_to_server(ChatServicer(),server)server.add_insecure_port('[::]:50051')awaitserver.start()print("gRPC server running on :50051")awaitserver.wait_for_termination()if__name__=='__main__':asyncio.run(serve())

✅ 使用grpc.aio(需grpcio>=1.39.0),天然支持async defasync for,避免线程阻塞,适合高并发场景。


✅ 步骤 4:客户端实现(异步双向流)

# client.pyimportasyncioimporttimeimportchat_pb2,chat_pb2_grpcasyncdefrun():asyncwithgrpc.aio.insecure_channel('localhost:50051')aschannel:stub=chat_pb2_grpc.ChatServiceStub(channel)# 创建双向流调用call=stub.Chat()# 启动发送协程(模拟用户输入)asyncdefsend_messages():foriinrange(3):msg=chat_pb2.ChatMessage(sender="client",message=f"Hello #{i+1}",timestamp=int(time.time()))awaitcall.write(msg)awaitasyncio.sleep(1)awaitcall.done_writing()# 告知服务端发送结束(可选,但推荐)# 启动接收协程asyncdefrecv_messages():asyncforresponseincall:print(f"[Client] Received:{response.message}(from{response.sender})")# 并发执行收发awaitasyncio.gather(send_messages(),recv_messages())if__name__=='__main__':asyncio.run(run())

⚠️ 关键点:

  • call = stub.Chat()返回一个grpc.aio.StreamStreamCall对象;
  • call.write()发送单条消息,call.done_writing()显式结束写入(否则服务端可能永远等待);
  • async for response in call持续接收服务端推送的消息;
  • 必须用asyncio.gather并发处理读写,否则会因await call.write()阻塞接收。

🔁 补充:同步版(不推荐高并发,仅作兼容参考)

若必须用同步grpc(非aio),需在独立线程中运行iter(call)+call.send(),并手动管理线程/队列,复杂度高、易出错,故强烈建议优先采用grpc.aio


典型应用场景:实时聊天、IoT 设备指令与状态双向同步、协同编辑、日志/指标流式上报等。