grpc入门

grpc是google公司开发的远程调用协议rpc. 官网https://www.grpc.io/

必备条件

  • 生成工具

    • protoc
      • apt 安装
  • 插件

    • go语言插件(go install 安装)
      • protoc-gen-go
      • protoc-gen-go-grpc

步骤

  • 定义proto文件

    syntax = "proto3";
    
    option go_package = "pb/";
    
    package pb;
    
    service HelloService {
        rpc Hello(HelloRequest) returns (HelloReplay) {}
    }
    
    message HelloRequest {
        string name = 1;
    }
    
    message HelloReplay {
        string message = 1;
    }
    
  • 服务端

    • main.go
    package main
    
    import (
    	"hello/pb"
    	"net"
    
    	"google.golang.org/grpc"
    )
    
    func main() {
    	lis, err := net.Listen("tcp4", ":9000")
    	if err != nil {
    		panic(err)
    	}
    
    	s := grpc.NewServer()
    
    	pb.RegisterHelloServiceServer(s, &server{})
    	err = s.Serve(lis)
    	if err != nil {
    		panic(err)
    	}
    }
    
    
    • server.go
    package main
    
    import (
    	"context"
    	"hello/pb"
    )
    
    type server struct {
    	pb.UnimplementedHelloServiceServer
    }
    
    func (s *server) Hello(ctx context.Context, in *pb.HelloRequest) (out *pb.HelloReplay, err error) {
    	out = &pb.HelloReplay{
    		Message: "Hello," + in.GetName(),
    	}
    	return
    }
    
    
  • 客户端

    • main.go
    package main
    
    import (
    	"context"
    	"log"
    	"time"
    
    	"google.golang.org/grpc"
    
    	"hello/pb"
    )
    
    func main() {
    	conn, err := grpc.Dial("127.0.0.1:9000", grpc.WithInsecure())
    	if err != nil {
    		panic(err)
    	}
    
    	defer conn.Close()
    	c := pb.NewHelloServiceClient(conn)
    
    	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    	defer cancel()
    	r, err := c.Hello(ctx, &pb.HelloRequest{Name: "桥三"})
    	if err != nil {
    		panic(err)
    	}
    	log.Printf("还: %s", r.GetMessage())
    }
    
    
posted @ 2022-06-14 11:39  jiftle  阅读(88)  评论(0编辑  收藏  举报