• grpc详细入门


    引用网址:https://zhuanlan.zhihu.com/p/270216882

    所谓RPC(remote procedure call 远程过程调用)框架实际是提供了一套机制,使得应用程序之间可以进行通信,而且也遵从server/client模型。使用的时候客户端调用server端提供的接口就像是调用本地的函数一样。

    grpc原理:
    比如 A (client) 调用 B (server) 提供的remoteAdd方法:
    首先,A与B之间建立一个TCP连接;
    然后,A把需要调用的方法名(这里是remoteAdd)以及方法参数(10, 20)序列化成字节流发送出去;
    接着,B接受A发送过来的字节流,然后反序列化得到目标方法名,方法参数,接着执行相应的方法调用(可能是localAdd)并把结果30返回;
    最后,A接受远程调用结果,输出30。
    RPC框架就是把我刚才说的这几点些细节给封装起来,给用户暴露简单友好的API使用。

    gRPC的优势,如下:
    1.gRPC可以通过protobuf来定义接口,从而可以有更加严格的接口约束条件。
    2.通过protobuf可以将数据序列化为二进制编码,这会大幅减少需要传输的数据量,从而大幅提高性能。
    3.gRPC可以方便地支持流式通信。

    流程:
    1.创建接口文件---- .proto文件

    syntax = "proto3";  //语法声明
    
    package helloworld; //包名
    
    // Greeter 微服务,定义一个RPC服务并具有一个方法,该方法接收HelloRequest,并返回一个HelloReply,此时可以在.proto文件中进行如下定义:
    service Greeter {
      // Sends a greeting
      rpc SayHello (HelloRequest) returns (HelloReply) {}
    }
    //生成的接口代码作为客户端与服务端的约定,服务端必须实现定义的所有接口方法,客户端直接调用同名方法向服务端发起请求。
    
    // HelloRequest 请求数据格式,message对应golang中的struct
    message HelloRequest {
      string name = 1;
    }
    
    // HelloReply 响应数据格式
    message HelloReply {
      string message = 1;
    }

    将proto文件编译成go文件,生成golang的服务代码

    protoc -I helloworld/ helloworld/helloworld.proto --go_out=plugins=grpc:helloworld

    2.服务端代码

    package main
    
    import (
        "context"
        "log"
        "net"
    
        "google.golang.org/grpc"
        pb "google.golang.org/grpc/examples/helloworld/helloworld"
        "google.golang.org/grpc/reflection"
    )
    
    const (
        port = ":50051"
    )
    
    
    type server struct{} //服务对象
    
    // SayHello 实现服务的接口 在proto中定义的所有服务都是接口
    func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
        return &pb.HelloReply{Message: "Hello " + in.Name}, nil
    }
    
    func main() {
        lis, err := net.Listen("tcp", port)
        if err != nil {
            log.Fatalf("failed to listen: %v", err)
        }
        s := grpc.NewServer() //起一个服务 
        pb.RegisterGreeterServer(s, &server{})
        // 注册反射服务 这个服务是CLI使用的 跟服务本身没有关系
        reflection.Register(s)
        if err := s.Serve(lis); err != nil {
            log.Fatalf("failed to serve: %v", err)
        }
    }

    3.客户端代码

    package main
    
    import (
        "context"
        "log"
        "os"
        "time"
    
        "google.golang.org/grpc"
        pb "google.golang.org/grpc/examples/helloworld/helloworld"
    )
    
    const (
        address     = "localhost:50051"
        defaultName = "world"
    )
    
    func main() {
        //建立链接
        conn, err := grpc.Dial(address, grpc.WithInsecure())
        if err != nil {
            log.Fatalf("did not connect: %v", err)
        }
        defer conn.Close()
        c := pb.NewGreeterClient(conn)
    
        // Contact the server and print out its response.
        name := defaultName
        if len(os.Args) > 1 {
            name = os.Args[1]
        }
        // 1秒的上下文
        ctx, cancel := context.WithTimeout(context.Background(), time.Second)
        defer cancel()
        r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})
        if err != nil {
            log.Fatalf("could not greet: %v", err)
        }
        log.Printf("Greeting: %s", r.Message)
    }

    4.字段规则

    repeated: 标识字段可以重复任意次,类似数组。

    5.默认值:

    字符串类型默认为空字符串
    字节类型默认为空字节
    布尔类型默认false
    数值类型默认为0值
    enums类型默认为第一个定义的枚举值,必须是0

  • 相关阅读:
    Github精选——devops一体化监控平台工具WGCLOUD
    [搬运][中英双语]字体推荐 | 如果你每天都在代码面前,为何不让其变得有趣起来呢?
    【学习笔记】二分图最大匹配 -- 从网络流到匈牙利算法
    【详细揭秘】多重集の交错排列
    支配树口胡
    题解 洛谷 P2388 阶乘之乘
    [eJOI2019]异或橙子 题解
    VBA (Excel) 插入多行的方法 & 算法对比
    20000套免费ppt模板获取攻略
    包你扫到敬业福,集五福活动,福字大全
  • 原文地址:https://www.cnblogs.com/bruce1992/p/15768154.html
Copyright © 2020-2023  润新知