gRPC开发入门

来源:互联网 发布:如何做淘宝详情页 编辑:程序博客网 时间:2024/05/19 08:42

最近在做项目的过程中遇到了需要使用RPC的情况,那么就选择了Google开发的gRPC框架,就简单了学一下,对其有了简单的了解,那么就记录一下,首先介绍一下什么是rpc,然后是grpc,再者是尝试用Python客户端以及Golang服务端来完成一个计算加减乘除的功能。


一、gRPC
RPC,即Remote Procedure Call Protocol--远程过程调用协议,它是一种通过网络从远程计算机程序上请求服务,而不需要了解底层网络技术的协议。在客户端本地调用函数就像是在本地一样,而实际上是通过网络协议传输到服务端并计算然后得到返回值。RPC采用C/S模式,请求程序是一个客户机,而服务提供程序就是一个服务器。

gRPC是一个高性能、通用的开源RPC框架,基于ProtoBuf(Protocol Buffers)序列化协议开发,且支持众多开发语言,如Golang,Java,Python等等。


二、Protocol Buffer

Protocol Buffer是一种轻便高效的结构化数据存储格式,可以用于结构化数据串行化,或者说序列化。很适合做数据存储或者RPC数据交换格式。可用于协议通信、数据存储等领域的与语言无关,平台无关,可扩展的序列化结构数据格式。

三、安装protoc

protoc是编译.proto文件的编译器,生成对应语言的文件以供客户端和服务端调用。

git clone https://github.com/google/protobuf.gitcd protobuf./autogen.sh./configuremake && make install
如果在make过程中遇到"metadata.h"问题,那么通过修改源码解决:https://github.com/google/protobuf/pull/2599


四、编写proto文件

syntax = "proto3";package calculation;service Calc{                                                                                                                                                                                    rpc Calculate (CalcRequest) returns (CalcResult){}}message CalcRequest {    int32 a = 1;    int32 b = 2;    string operation = 3;}message CalcResult {    int32 result = 1;}

注:

1.我们定义了请求的message CalcRequest,两个数为a和b,操作符为operation;返回的message为CalcResult,其中包含一个值为result


五、编译proto文件

以Python为例。

python -m pip install grpciopython -m pip install grpcio-toolsPython生成客户端和服务端代码:python -m grpc_tools.protoc -I../../protos --python_out=. --grpc_python_out=. ../../protos/calculation.proto
那么在当前的目录下会生成两个文件:calculation_pb2_grpc.py和calculation_pb2.py。然后自己再编写客户端和服务端程序就好了。


六、C/S端程序

client:calculation_client.py:

import grpcimport calculation_pb2import calculation_pb2_grpcdef run():    channel = grpc.insecure_channel("localhost:50052")    stub = calculation_pb2_grpc.CalcStub(channel)    response = stub.Calculate(calculation_pb2.CalcRequest(a=8,b=4,operation="/"))    print("calculation result received:  %d" %  response.result)if __name__ == '__main__':    run()
server:calculation_server.py:

import timeimport grpcimport calculation_pb2import calculation_pb2_grpc_TIME_WAIT = 10class Calc(calculation_pb2_grpc.CalcServicer):    def Calculate(self, request, context):        opera = request.operation        if opera == '+':            res = request.a + request.b            return calculation_pb2.CalcResult(result = res)        elif opera == '-':            res = request.a - request.b            return calculation_pb2.CalcResult(result = res)        elif opera == '*':            res = request.a * request.b            return calculation_pb2.CalcResult(result = res)        else:            res = request.a / request.b            return calculation_pb2.CalcResult(result = res)def serve():    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))    calculation_pb2_grpc.add_CalcServicer_to_server(Calc(), server)    server.add_insecure_port('[::]:50052')    server.start()    try:        while True:            time.sleep(_TIME_WAIT)    except KeyboardInterrupt:        server.stop(0)if __name__ == '__main__':    serve()

在客户端我们将a和b以及operation的值hard code了。计算的为8/4,结果为2。在运行的时候先启动server端,在启动client端。



对于golang,编译proto文件的过程类似:

Golang RPChttps://github.com/grpc/grpc-go/tree/master/examples

go get -a github.com/golang/protobuf/protoc-gen-goprotoc -I . ./protos/calculation.proto --go_out=plugins=grpc:calculation

然后再编写client和server端的程序即可。


Author:忆之独秀

Email:leaguenew@qq.com

注明出处:http://blog.csdn.net/lavorange/article/details/74504837




原创粉丝点击