gRPC入门教程

Overview

gRPC 是一个现代开源的高性能远程过程调用 (RPC) 框架,可以在任何环境中运行。它可以通过对负载平衡、跟踪、健康检查和身份验证的可插拔支持有效地连接数据中心内和跨数据中心的服务。它也是适用于分布式计算的最后一英里,将设备、移动应用程序和浏览器连接到后端服务。

gRPC使用protocol buffers作为Interface Definition Language (IDL),client端使用方法stub,server端有同样方法实现.

优点

gRPC一个高性能、开源的通用 RPC 框架,主要特点:

  1. 服务定义简单:仅需使用Protocol Buffers就完成service定义
  2. 启动快速可扩展:只需一行即可安装运行和开发环境,还可以使用该框架扩展到每秒数百万个 RPC
  3. 跨语言和平台:自动化生成各种语言和平台服务客户端和服务器存根
  4. 双向流式且集成身份验证:双向流式传输和完全集成的可插拔身份验证以及基于 HTTP/2 的传输

Protocol Buffer编译器安装

  • 在线安装
//Linuxapt install -y protobuf-compilerprotoc --version//Macbrew install protobufprotoc --version  # Ensure compiler version is 3+

  • 二进制文件安装
PB_REL="https://github.com/protocolbuffers/protobuf/releases"curl -LO $PB_REL/download/v3.15.8/protoc-3.15.8-linux-x86_64.zipunzip protoc-3.15.8-linux-x86_64.zip -d $HOME/.localexport PATH="$PATH:$HOME/.local/bin"

Go plugins安装

go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2


.proto文件中定义Service

Protocol buffer结构化数据使用 messages 定义,其中每条message都是一个小的信息逻辑记录,包含一系列称为字段的name-value值对。如 hello.proto

syntax = "proto3";option go_package = "github.com/gs-samples/grpc/helloworld";package helloworld;// The greeting service definition.service Greeter {  // Sends a greeting  rpc SayHello (HelloRequest) returns (HelloReply) {}}// The request message containing the user's name.message HelloRequest {  string name = 1;}// The response message containing the greetingsmessage HelloReply {  string message = 1;}

生成gRPC代码

指定proto文件路径,执行protoc命令

protoc --go_out=. --go_opt=paths=source_relative \                                           ✔  10514  16:49:50     --go-grpc_out=. --go-grpc_opt=paths=source_relative \    helloworld/hello.proto

执行后生成helloworld/helloworld.pb.go 和 helloworld/helloworld_grpc.pb.go

生成pb代码中,依赖

google.golang.org/grpc v1.36.0google.golang.org/protobuf v1.28.0

Server与Client测试

package grpcimport (   "context"   "fmt"   pb "go-samples/rpc/grpc/helloworld"   "google.golang.org/grpc"   "google.golang.org/grpc/credentials/insecure"   "log"   "net"   "testing"   "time")const (   addr = "localhost:50051"   port = "50051")func TestClientCall(t *testing.T) {   go startServer()   time.Sleep(time.Second * 2)   conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))   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.   ctx, cancel := context.WithTimeout(context.Background(), time.Second)   defer cancel()   r, err := c.SayHello(ctx, &pb.HelloRequest{Name: "world1"})   if err != nil {      log.Fatalf("could not greet: %v", err)   }   log.Printf("Greeting: %s", r.GetMessage())}func startServer() {   lis, err := net.Listen("tcp", fmt.Sprintf(":%v", port))   if err != nil {      log.Fatalf("failed to listen: %v", err)   }   s := grpc.NewServer()   pb.RegisterGreeterServer(s, &server{})   log.Printf("server listening at %v", lis.Addr())   if err := s.Serve(lis); err != nil {      log.Fatalf("failed to serve: %v", err)   }}// server is used to implement helloworld.GreeterServer.type server struct {   pb.UnimplementedGreeterServer}// SayHello implements helloworld.GreeterServerfunc (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {   log.Printf("Received: %v", in.GetName())   return &pb.HelloReply{Message: "Server reply--->Hello " + in.GetName()}, nil}
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章