gRPC入门教程

Overview

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

gRPC入门教程

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

优点

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

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

Protocol Buffer编译器安装

//Linux
apt install -y protobuf-compiler
protoc --version

//Mac
brew install protobuf
protoc --version  # Ensure compiler version is 3+
gRPC入门教程

PB_REL="https://github.com/protocolbuffers/protobuf/releases"
curl -LO $PB_REL/download/v3.15.8/protoc-3.15.8-linux-x86_64.zip
unzip protoc-3.15.8-linux-x86_64.zip -d $HOME/.local
export PATH="$PATH:$HOME/.local/bin"

Go plugins安装

go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28
go 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 greetings
message 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

gRPC入门教程

生成pb代码中,依赖

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

Server与Client测试

package grpc

import (
   "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.GreeterServer
func (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
}
展开阅读全文

页面更新:2024-05-12

标签:在线   存根   双向   数据中心   框架   入门教程   定义   语言   代码   环境   文件

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号

Top