美文网首页go
快速开始使用grpc(golang版)

快速开始使用grpc(golang版)

作者: 你家旭哥 | 来源:发表于2018-12-03 17:05 被阅读24次

    开始前准备

    安装gprc

    go get -u google.golang.org/grpc

    安装protocol buffers

    protoc编译器这个用于生成gRPC服务代码的。
    下载解压后放入PATH路径,供后续使用。接下来安装protoc的go语言的插件go get -u github.com/golang/protobuf/protoc-gen-go

    注意:这边插件也必须要在PATH路径下

    栗子 采用$GOPATH/src/google.golang.org/grpc/examples/helloworld的栗子

    新建helloworld.proto,这个文件可以供多人使用。

    syntax = "proto3";  //语法声明
    
    package helloworld; //包名
    
    // Greeter 微服务
    service Greeter {
      // Sends a greeting
      rpc SayHello (HelloRequest) returns (HelloReply) {}
    }
    
    // HelloRequest 请求数据格式
    message HelloRequest {
      string name = 1;
    }
    
    // HelloReply 响应数据格式
    message HelloReply {
      string message = 1;
    }
    

    生成golang的服务代码
    protoc -I helloworld/ helloworld/helloworld.proto --go_out=plugins=grpc:helloworld
    这个指令支持*.proto模糊匹配。如果有许多文件可以使用helloworld/*.proto 来作为PROTO_FILES

    服务端代码

    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)
        }
    }
    
    

    客户端代码

    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)
    }
    
    

    总结:grpc所构建的服务可以作为微服务使用,供接口或者其他模块使用。

    相关文章

      网友评论

        本文标题:快速开始使用grpc(golang版)

        本文链接:https://www.haomeiwen.com/subject/oswycqtx.html