RPC是远程过程调用(Remote Procedure Call)
GRPC是google出的高性能、开源的通用RPC框架
优点: 1、接口有更严格的约束 2、更安全 3、性能更好 。
这3个优点来源于gRPC使用的protobuf(一种数据传输格式和规范)
ERP系统
SAP系统
构建一个GPRC helloworld项目:
1、项目目录结构
grpc_helloworld:
protos
helloworld.proto
rpc_package
__init__.py
helloworld_pb2.py
helloworld_pb2_grpc.py
hello_server.py
hello_client.py
2、安装protobuf依赖
pip install grpcio-tools
3、通过protobuf来定义接口和数据类型
helloworld.proto如下:
syntax = "proto3";
package rpc_package;
// define a service
service HelloWorldService {
// define the interface and data type
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// define the data type of request
message HelloRequest {
string name = 1;
}
// define the data type of response
message HelloReply {
string message = 1;
}
4、使用gRPC protobuf生成工具生成对应语言的库函数
python -m grpc_tools.protoc -I=./protos --python_out=./rpc_package --grpc_python_out=./rpc_package ./protos/helloworld.proto
5、编写gRPC server端代码
hello_server.py如下:
from concurrent import futures
import grpc
import logging
import time
from rpc_package.helloworld_pb2_grpc import add_HelloWorldServiceServicer_to_server, \
HelloWorldServiceServicer
from rpc_package.helloworld_pb2 import HelloRequest, HelloReply
class Hello(HelloWorldServiceServicer):
# 这里实现我们定义的接口
def SayHello(self, request, context):
return HelloReply(message='Hello, %s!' % request.name)
def serve():
# 这里通过thread pool来并发处理server的任务
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
# 将对应的任务处理函数添加到rpc server中
add_HelloWorldServiceServicer_to_server(Hello(), server)
# 这里使用的非安全接口,世界gRPC支持TLS/SSL安全连接,以及各种鉴权机制
server.add_insecure_port('[::]:50000')
server.start()
try:
while True:
time.sleep(60 * 60 * 24)
except KeyboardInterrupt:
server.stop(0)
if __name__ == "__main__":
logging.basicConfig()
serve()
6、编写gRPC client端代码
hello_client.py如下:
from __future__ import print_function
import logging
import grpc
from rpc_package.helloworld_pb2 import HelloRequest, HelloReply
from rpc_package.helloworld_pb2_grpc import HelloWorldServiceStub
def run():
# 使用with语法保证channel自动close
with grpc.insecure_channel('localhost:50000') as channel:
# 客户端通过stub来实现rpc通信
stub = HelloWorldServiceStub(channel)
# 客户端必须使用定义好的类型,这里是HelloRequest类型
response = stub.SayHello(HelloRequest(name='eric'))
print("hello client received: " + response.message)
if __name__ == "__main__":
logging.basicConfig()
run()
7、进入虚拟环境,运行server
python hello_server.py
8、运行client
python hello_client.py