grpc简介
gRPC是一个高性能、通用的开源RPC框架,其由Google主要面向移动应用开发并基于HTTP/2协议标准而设计,基于ProtoBuf序列化协议开发,且支持众多开发语言。具体大家可以在gRPC的官网查看。
搭建python grpc服务
- 我们用的python3.6,第一步淡然是安装python需要的库
pip install grpcio
pip install grpcio-tools 主要是为了将pb编译成python
pip install protobuf
- 开发protobuf文件,protobuf版本用的proto3。名称位test.proto
syntax = "proto3";
option cc_generic_services = true;
service GrpcService {
rpc hello (HelloRequest) returns (HelloResponse) {}
}
//请求的pb
message HelloRequest {
string data = 1;
};
//返回的对象
message HelloResponse {
string result = 1;
};
- 开发完成后,我们要将pb文件转化成python文件,直接在当前文件目录下面执行
python -m grpc_tools.protoc -I./ --python_out=./ --grpc_python_out=./ ./test.proto
执行完后会生成一个test_pb2.py和test_pb3_grpc.py
- 接下来我们开发grpc的服务端,service.py
#! /usr/bin/env python
# coding=utf8
import time
from concurrent import futures
import grpc
from service import test_pb2_grpc, test_pb2
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
class TestService(test_pb2_grpc.GrpcServiceServicer):
'''
继承GrpcServiceServicer,实现hello方法
'''
def __init__(self):
pass
def hello(self, request, context):
'''
具体实现hello的方法,并按照pb的返回对象构造HelloResponse返回
:param request:
:param context:
:return:
'''
result = request.data + " this is gprc test service"
return test_pb2.HelloResponse(result=str(result))
def run():
'''
模拟服务启动
:return:
'''
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
test_pb2_grpc.add_GrpcServiceServicer_to_server(TestService(),server)
server.add_insecure_port('127.0.0.1:9098')
server.start()
print("start service...")
try:
while True:
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__':
run()
- 继续开发grpc的客户端请求,client.py
#! /usr/bin/env python
# coding=utf8
import grpc
from service import test_pb2_grpc, test_pb2
def run():
'''
模拟请求服务方法信息
:return:
'''
conn=grpc.insecure_channel("127.0.0.1:9098")
client = test_pb2_grpc.GrpcServiceStub(channel=conn)
respnse = client.hello(test_pb2.HelloRequest(data="xiao li"))
print("received:",respnse.result)
if __name__ == '__main__':
run()
- 测试我们的结果,先启动service.py服务,然后执行client.py,会直接返回
received: xiao li this is gprc test service
其他
这里只是一个简单的grpc服务简单,具体我们可以通过http的形式暴露成http的接口对外访问,实际中要根据业务场景,对外提供不同的grpc服务