1:grpc官方文档
grpc是支持多语言的,我们先用python体验一下。
虚拟环境还是之前安装过的包
2:先看目录
3:helloworld.proto
helloworld.proto是protobuf模板文件用来生成python文件,代码如下
python -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I . helloworld.proto
以上代码会生成两个文件一个
helloworld_pb2.py 按照模板文件生成的类和函数在这里面,调用的时候从这里面导入即可
helloworld_pb2_grpc.py 用到的grpc方法从这里面导入
syntax = "proto3";
service Greeter {
// SayHello是函数,HelloRequest是参数,HelloReply是返回值,
// HelloRequest和HelloReply必须是下面的message
rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
4:server.py
from concurrent import futures
import grpc
from helloworld_pb2 import HelloReply
from helloworld_pb2_grpc import GreeterServicer, add_GreeterServicer_to_server
class Greeter(GreeterServicer):
def SayHello(self, request,context):
return HelloReply(message=f"你好,{request.name}")
if __name__ == "__main__":
# 实例化server
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
# 注册函数方法到grpc中去
add_GreeterServicer_to_server(Greeter(), server)
# 启动服务
server.add_insecure_port('0.0.0.0:8808')
server.start()
# 防止主程序退出
server.wait_for_termination()
5:client.py
import grpc
from helloworld_pb2_grpc import GreeterStub
from helloworld_pb2 import HelloRequest,HelloReply
if __name__ == "__main__":
# 创建连接
with grpc.insecure_channel("localhost:8808") as channel:
"""
实例化GreeterStub类,这个类帮我们封装了,调用服务端函数的业务逻辑
调用服务端的函数是channel对象完成的所以需要传入它
封装解耦的内容都在GreeterStub的SayHello的方法里,SayHello和我们代码SayHello是两个函数,
stub.SayHello时,也调用了channel的"call"方法,"call"方法是要传很多参数的,所以需要封装
为了让程序员使用更简单。
因为GreeterStub继承了channel的类,stub既可以调用自己的SayHello,也能调用channel的“call”
ps:
这里的"call"是类比之前go语言rpc里的call方法,这里名字肯定不一样,但功能肯定是类似的。
"""
stub = GreeterStub(channel)
res: HelloReply = stub.SayHello(HelloRequest(name="Book"))
print(res.message)