在现代微服务架构中,gRPC Python 已成为高性能、跨语言通信的重要工具。本文将带你从零开始,手把手教你如何使用 gRPC库 构建一个完整的客户端-服务器通信系统。无论你是刚接触gRPC的新手,还是想巩固基础知识的开发者,这篇Python gRPC教程都能让你轻松上手。

gRPC 是 Google 开发的高性能、开源的远程过程调用(RPC)框架,它基于 HTTP/2 协议,并使用 Protocol Buffers(简称 Protobuf)作为接口定义语言(IDL)。相比传统的 REST API,gRPC 具有更低的延迟、更高的吞吐量和更强的类型安全性。
而 gRPC Python 就是 gRPC 官方为 Python 语言提供的实现库,允许你用 Python 编写 gRPC 服务端和客户端。
在开始编码前,请确保你的系统已安装以下工具:
接下来,安装 gRPC 相关依赖:
pip install grpcio grpcio-tools protobufgRPC 使用 .proto 文件来定义服务和消息格式。我们创建一个名为 hello.proto 的文件:
syntax = "proto3";package helloworld;// 定义服务service Greeter { // 一个简单的 SayHello 方法 rpc SayHello (HelloRequest) returns (HelloReply);}// 请求消息message HelloRequest { string name = 1;}// 响应消息message HelloReply { string message = 1;}使用 grpc_tools.protoc 工具将 .proto 文件编译成 Python 代码:
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. hello.proto执行后会生成两个文件:
hello_pb2.py:包含消息类(如 HelloRequest 和 HelloReply)hello_pb2_grpc.py:包含服务类和 stub(客户端代理)创建 server.py 文件:
import grpcfrom concurrent import futuresimport timeimport hello_pb2import hello_pb2_grpcclass GreeterServicer(hello_pb2_grpc.GreeterServicer): def SayHello(self, request, context): return hello_pb2.HelloReply(message=f'Hello, {request.name}!')def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) hello_pb2_grpc.add_GreeterServicer_to_server(GreeterServicer(), server) server.add_insecure_port('[::]:50051') server.start() print("Server started on port 50051") try: while True: time.sleep(86400) # 保持服务运行 except KeyboardInterrupt: server.stop(0)if __name__ == '__main__': serve()创建 client.py 文件:
import grpcimport hello_pb2import hello_pb2_grpcdef run(): with grpc.insecure_channel('localhost:50051') as channel: stub = hello_pb2_grpc.GreeterStub(channel) response = stub.SayHello(hello_pb2.HelloRequest(name='Alice')) print("Server response: " + response.message)if __name__ == '__main__': run()先启动服务端:
python server.py再打开另一个终端运行客户端:
python client.py如果一切正常,你会看到输出:
Server response: Hello, Alice!通过本篇gRPC入门教程,你已经掌握了如何使用 gRPC Python 库构建一个完整的 gRPC 应用。从定义 .proto 文件到生成代码,再到编写服务端和客户端,每一步都清晰明了。
gRPC 不仅适用于微服务通信,也广泛应用于移动后端、IoT 设备等场景。希望这篇教程能为你打开 gRPC 的大门!
如果你觉得有用,不妨动手实践一下,尝试添加更多方法或使用 TLS 加密通信,进一步提升你的 Python gRPC教程 实战能力。
本文由主机测评网于2025-12-14发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025127611.html