【Python小随笔】 Grpc协议的使用
协议
gRPC(Google Remote Procedure Call)是一种高性能、开源的远程过程调用(RPC)框架,由Google开发并开源。它基于HTTP/2协议进行通信,使用Protocol Buffers(protobuf)作为接口定义语言(IDL)。
gRPC提供了跨平台、跨语言的服务端和客户端的通信能力。它使用IDL定义服务接口和数据结构,自动生成服务端和客户端的代码,使得开发者可以专注于业务逻辑的实现,而不必手动处理底层的网络通信部分。
gRPC具有以下特点:
1. 高效性:使用HTTP/2协议进行通信,支持多路复用、请求和响应首部压缩等特性,减少了网络开销和延迟。
2. 跨语言支持:支持多种编程语言,包括但不限于Python、Java、Go、C++等,使得不同语言的服务端和客户端可以无缝通信。
3. 强类型约束:使用Protocol Buffers作为接口定义语言,提供了强类型约束和版本管理,方便接口的演进和扩展。
4. 可插拔的拦截器:支持自定义拦截器,可以在请求和响应的处理过程中进行拦截和修改,实现自定义的逻辑。
5. 双向流式通信:支持双向流式通信,服务端和客户端可以同时发送和接收多个消息,实现实时的双向通信。
6. 安全性:支持基于TLS的安全通信,保证通信过程的安全性。
总而言之,gRPC是一个功能强大、高效性能、跨平台、跨语言的RPC框架,适用于构建分布式系统和微服务架构。它可以简化服务间的通信,提高开发效率,并具有良好的扩展性和可维护性。
定义接口
// test.proto
syntax = "proto3";
option cc_generic_services = true;
service Greeter {
// 第一个接口
rpc One(OneRequest) returns (OneResponse) {}
// 第二个接口
rpc Two(TwoRequest) returns (TwoResponse) {}
}
// 第1个接口 请求值
message OneRequest {
string name = 1;
}
// 第1个接口 返回值
message OneResponse {
string message = 1;
}
// 第2个接口 请求值
message TwoRequest {
string age = 2;
}
// 第2个接口 返回值
message TwoResponse {
string message = 2;
}
执行编译命令
python -m grpc_tools.protoc -I . --python_out=./ --pyi_out=./ --grpc_python_out=./ ./test.proto
创建服务端
# grpc_server.py
import test_pb2,test_pb2_grpc
import grpc
from concurrent import futures
# 继承生成的Server类做逻辑接口
class Greeter(test_pb2_grpc.GreeterServicer):
"""
注意:
这里函数的命名需要跟proto文件里面的接口名字一致
"""
def One(self, request, context):
# 第1个逻辑接口
return test_pb2.OneResponse(message='Hello, ' + request.name)
def Two(self, request, context):
# 第2接口逻辑接口
return test_pb2.TwoResponse(message='Goodbye, ' + request.name)
# 启动服务端
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
test_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port('[::]:8800')
server.start()
print("启动成功,等待接受数据...")
server.wait_for_termination()
if __name__ == '__main__':
serve()
客户端
# grpc_client.py
import grpc
import test_pb2,test_pb2_grpc
def run():
# 创建连接
channel = grpc.insecure_channel('127.0.0.1:8800')
# 创建客户端
client = test_pb2_grpc.GreeterStub(channel)
# 创建 传参值
obj = test_pb2.OneRequest(name="IM")
# 请求接口
response = client.One(obj)
print("response",response)
if __name__ == '__main__':
run()
Python全栈(后端、数据分析、脚本、爬虫、EXE客户端) / 前端(WEB,移动,H5) / Linux / SpringBoot / 机器学习

浙公网安备 33010602011771号