grpc框架_grpc的入门使用

dc8236d2e85c5403ebdfdc0de2895d49.png

前言

grpc是一个高性能、通用的开源RPC框架,基于HTTP/2协议标准和Protobuf序列化协议开发,支持众多的开发语言。在对接口具有严格约束或者传递大量数据的场景中得到了广泛的应用。本文作者从什么是grpc开始介绍,讲诉了protobuf的语法以及如何使用grpc框架,对于想学习grpc的初学者来说,是一篇极好的入门教程,下来就跟随作者一起学习吧。

简介

什么是grpc

grpc是一个由google推出的、高性能、开源、通用的rpc框架。它是基于HTTP2协议标准设计开发,默认采用Protocol Buffers数据序列化协议,支持多种开发语言。

什么是protobuf buffers

ProtoBuf buffer 是一种数据表达方式,以.proto结尾的数据文件,可以类比json、xml等。针对ProtoBuf buffer 数据源,可以利用protoc 工具来生成各种语言的访问类。

其操作步骤:

  1. 定义数据元;
  2. 生成数据元的访问类。

优点:

  • 编解码速度更快;
  • 传输的数据更小。

protobuf buffers定义数据元的语法

一个.proto文件,主要包括以下部分:

syntax = "proto3";package studentpb;service Student {     rpc add (StudentReqs) returns (StudentReply) {} //新增学生接口}message StudentReqs {    repeated StudentReq s = 1;}message StudentReq{    string name= 1;    int32 age = 2;}message StudentReply {    int32 errno = 1;    string errmsg = 2;}
  • 关键字syntax:指定使用的proto3语法;
  • 关键字package:定义一个包,需要注意避免命名冲突;
  • 关键字message来定义请求或相应需要使用的消息格式,里面可以包含了不同类型的字段 。一个.proto文件中,可以包含多个message的定义。
  • 关键字server来定一个服务。GRPC的服务是通过参数和返回类型来指定可以远程调用的方法。

字段的约束规则

  • repeated:前置repeated关键词,声明该字段为数组类型。
  • proto3不支持proto2中的required和optional关键字。

字段支持的类型

支持基础类型、枚举类型、map类型、数组类型、message类型等。

  • 基础类型
66390f97eb281eee8749c381b88d5187.png
  • 枚举类型
syntax = "proto3";message Student{  string name = 1;  // 定义enum类型  enum Sex {    BOY = 0;    GIRL = 1;  }  Sex sex = 1; // 使用Corpus作为字段类型}
  • message类型
syntax = "proto3";message Students {    repeated Student s = 1;}message Student{  string name = 1;  // 定义enum类型  enum Sex {    BOY = 0;    GIRL = 1;  }  Sex sex = 4; // 使用Corpus作为字段类型}

如何利用protoc 工具生成访问类

prooc常用参数

26fcea1a0452effaee076d7ca0ac7160.png

案例

文件目录如下:

0ff93e115ef434e99c8ad1ec626dfc83.png

其中“t.proto”内容如下:

syntax = "proto3";package studentpb;service Student {     rpc add (StudentReqs) returns (StudentReply) {} //新增学生接口}message StudentReqs {    repeated StudentReq s = 1;}message StudentReq{    string name= 1;    int32 age = 2;}message StudentReply {    int32 errno = 1;    string errmsg = 2;}

生成go访问类的语句如下:

protoc --go_out=plugins=grpc:. protobuf/*.proto

GO如何利用GRPC通信

pb文件

syntax = "proto3";package studentpb;service Student {     rpc add (StudentReqs) returns (StudentReply) {} //新增学生接口}message StudentReqs {    repeated StudentReq s = 1;}message StudentReq{    string name= 1;    int32 age = 2;}message StudentReply {    int32 errno = 1;    string errmsg = 2;}

执行如下命令,生成grpc访问类

protoc --go_out=plugins=grpc:. *.proto

服务端

目录结构如下:

fc4d537b9f8ef45afd3b85bd99d9b1e9.png

main.go内容如下:

package mainimport (   "context"   "fmt"   "google.golang.org/grpc"   "log"   "net"   "test/studentpb")type Student struct {}// 新增studentsfunc (r *Student) Add(ctx context.Context, in *studentpb.StudentReqs) (*studentpb.StudentReply, error) {   return &studentpb.StudentReply{      Errno:  0,      Errmsg: "ok",   }, nil}func main() {   // 建立server监听   rpcAddr := "127.0.0.1:8601"   server, err := net.Listen("tcp", rpcAddr)   if err != nil {      fmt.Println("failed to listen", rpcAddr)      panic(err)   }   // 建立rpc server   var RpcServer = grpc.NewServer()   err = RpcServer.Serve(server)   if err != nil {      log.Fatalf("failed to listen: %v", err)   }   // 对外提供服务   r := new(Student)   studentpb.RegisterStudentServer(RpcServer, r)      select {   }}

用户端

目录结构如下:

package mainimport (   "context"   "fmt"   "google.golang.org/grpc"   "test/studentpb"   "time")func main() {   addr := "127.0.0.1:8601"   timeout := 10   //建立rpc通道   client, err := grpc.Dial(addr, grpc.WithInsecure())   if err != nil {      panic("连接失败")   }   defer client.Close()   // 创建studentrpc对象   rpcClient := studentpb.NewStudentClient(client)   // 创建上线文   ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)   defer cancel()   //封装请求参数   req := &studentpb.StudentReqs{}   req.S = append(req.S, &studentpb.StudentReq{Name:"张三", Age:12})   // 打印结果   res , err := rpcClient.Add(ctx, req)   if err != nil {      fmt.Println("请求错误", err)   } else {      fmt.Println(res.GetErrno(), res.GetErrmsg())   }}

关于360技术:360技术是360技术团队打造的技术分享公众号,每天推送技术干货内容,更多技术信息欢迎关注“360技术”微信公众号

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
gRPC 是一种高性能、开源的 RPC 框架,支持多种编程语言。在 Python ,我们可以使用 gRPC 提供远程过程调用服务。 以下是在 Python 使用 gRPC 的基本步骤: 1. 安装 gRPC使用 pip install grpcio 命令安装 gRPC。 2. 定义服务和消息:使用 proto3 编写 .proto 文件,定义服务和消息。 3. 生成代码:使用 protoc 命令生成 Python 代码。 4. 实现服务:在 Python 实现服务端和客户端。 5. 启动服务:启动服务端程序。 6. 调用服务:在客户端程序调用远程服务。 以下是一个简单的示例,演示如何在 Python 使用 gRPC: 1. 定义服务和消息 ```protobuf syntax = "proto3"; package helloworld; // 定义消息 message HelloRequest { string name = 1; } message HelloReply { string message = 1; } // 定义服务 service Greeter { rpc SayHello (HelloRequest) returns (HelloReply) {} } ``` 2. 生成代码 使用以下命令生成 Python 代码: ```bash python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. helloworld.proto ``` 3. 实现服务 在 Python 实现服务端和客户端。 ```python import grpc import helloworld_pb2 import helloworld_pb2_grpc class Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, context): return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) server.add_insecure_port('[::]:50051') server.start() server.wait_for_termination() if __name__ == '__main__': serve() ``` ```python import grpc import helloworld_pb2 import helloworld_pb2_grpc def run(): with grpc.insecure_channel('localhost:50051') as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) response = stub.SayHello(helloworld_pb2.HelloRequest(name='world')) print("Greeter client received: " + response.message) if __name__ == '__main__': run() ``` 4. 启动服务 在终端运行以下命令启动服务: ```bash python greeter_server.py ``` 5. 调用服务 在终端运行以下命令调用服务: ```bash python greeter_client.py ``` 以上是在 Python 使用 gRPC 的基本步骤。在生产环境,我们需要考虑更多的实现细节,例如错误处理、认证和安全等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值