gRPC 在 Go 中的应用:一个初步探索

2023-08-10 17:02:42 浏览数 (3)

引言

gRPC 是 Google 开发的一个高性能、开源的通用 RPC (Remote Procedure Call, 远程过程调用) 框架,其面向移动和 HTTP/2 设计,并且可以运行在任何环境中。它可以从任何应用程序中调用其他应用程序的方法,无论这些应用程序是在同一个主机上,还是分布在不同的主机上。gRPC 还为开发人员提供了简洁的服务定义框架,使得能够自动化生成客户端和服务器端的代码。

在本篇文章中,我们将探讨如何在 Go 语言环境中使用 gRPC,并解释协议(特别是 Protobuf,也就是 Protocol Buffers)和编码关系。

一、gRPC和Protobuf:定义并传递数据

gRPC 默认使用 Protobuf,这是 Google 的一种轻量级且高效的结构化数据存储格式。Protobuf 在定义服务和消息类型时表现得尤为强大,它能够简单且精确地定义数据结构,并且支持编译成多种语言的代码。

Protobuf 使用 .proto 文件来定义服务接口和消息结构。例如,我们可以定义一个简单的服务 Greeter,它有一个 SayHello 的 RPC 方法,接受一个 HelloRequest 消息,并返回一个 HelloResponse 消息:

代码语言:javascript复制
syntax = "proto3";
option go_package = "github.com/xiluo/myrpc/pb";
service Greeter {
  rpc SayHello (HelloRequest) returns (HelloResponse);
}

message HelloRequest {
  string name = 1;
}

message HelloResponse {
  string message = 1;
}

在上述代码中,Greeter 是我们定义的服务,SayHello 是服务中的方法,HelloRequestHelloResponse 则是我们定义的消息类型。每个字段都有一个唯一的数字标识,这些数字在 Protobuf 的二进制格式中用来标识字段。

二、从 Protobuf 到 Go:代码生成

安装插件:

代码语言:javascript复制
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 install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2
export PATH="$PATH:$(go env GOPATH)/bin"

一旦我们定义了 .proto 文件,我们就可以使用 Protobuf 编译器 protoc 以及 gRPC 的 Go 插件来生成对应的 Go 代码。这会生成我们服务中每个 RPC 方法的接口代码以及每个消息类型的数据结构代码。

代码语言:javascript复制
cd demomygrpcpb
protoc --go_out=. --go_opt=paths=source_relative 
  --go-grpc_out=. --go-grpc_opt=paths=source_relative 
  greeter.proto

代码:greeter.pb.go

代码语言:javascript复制
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
//   protoc-gen-go v1.28.1
//   protoc        v4.23.3
// source: greeter.proto

package pb  // 注意这里的包名

import (
  protoreflect "google.golang.org/protobuf/reflect/protoreflect"
  protoimpl "google.golang.org/protobuf/runtime/protoimpl"
  reflect "reflect"
  sync "sync"
)

const (
  // Verify that this generated code is sufficiently up-to-date.
  _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
  // Verify that runtime/protoimpl is sufficiently up-to-date.
  _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)

type HelloRequest struct {
  state         protoimpl.MessageState
  sizeCache     protoimpl.SizeCache
  unknownFields protoimpl.UnknownFields

  Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
}

func (x *HelloRequest) Reset() {
  *x = HelloRequest{}
  if protoimpl.UnsafeEnabled {
    mi := &file_greeter_proto_msgTypes[0]
    ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
    ms.StoreMessageInfo(mi)
  }
}

func (x *HelloRequest) String() string {
  return protoimpl.X.MessageStringOf(x)
}

func (*HelloRequest) ProtoMessage() {}

func (x *HelloRequest) ProtoReflect() protoreflect.Message {
  mi := &file_greeter_proto_msgTypes[0]
  if protoimpl.UnsafeEnabled && x != nil {
    ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
    if ms.LoadMessageInfo() == nil {
      ms.StoreMessageInfo(mi)
    }
    return ms
  }
  return mi.MessageOf(x)
}

// Deprecated: Use HelloRequest.ProtoReflect.Descriptor instead.
func (*HelloRequest) Descriptor() ([]byte, []int) {
  return file_greeter_proto_rawDescGZIP(), []int{0}
}

func (x *HelloRequest) GetName() string {
  if x != nil {
    return x.Name
  }
  return ""
}

type HelloResponse struct {
  state         protoimpl.MessageState
  sizeCache     protoimpl.SizeCache
  unknownFields protoimpl.UnknownFields

  Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"`
}

func (x *HelloResponse) Reset() {
  *x = HelloResponse{}
  if protoimpl.UnsafeEnabled {
    mi := &file_greeter_proto_msgTypes[1]
    ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
    ms.StoreMessageInfo(mi)
  }
}

func (x *HelloResponse) String() string {
  return protoimpl.X.MessageStringOf(x)
}

func (*HelloResponse) ProtoMessage() {}

func (x *HelloResponse) ProtoReflect() protoreflect.Message {
  mi := &file_greeter_proto_msgTypes[1]
  if protoimpl.UnsafeEnabled && x != nil {
    ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
    if ms.LoadMessageInfo() == nil {
      ms.StoreMessageInfo(mi)
    }
    return ms
  }
  return mi.MessageOf(x)
}

// Deprecated: Use HelloResponse.ProtoReflect.Descriptor instead.
func (*HelloResponse) Descriptor() ([]byte, []int) {
  return file_greeter_proto_rawDescGZIP(), []int{1}
}

func (x *HelloResponse) GetMessage() string {
  if x != nil {
    return x.Message
  }
  return ""
}

var File_greeter_proto protoreflect.FileDescriptor

var file_greeter_proto_rawDesc = []byte{
  0x0a, 0x0d, 0x67, 0x72, 0x65, 0x65, 0x74, 0x65, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22,
  0x22, 0x0a, 0x0c, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12,
  0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e,
  0x61, 0x6d, 0x65, 0x22, 0x29, 0x0a, 0x0d, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x73, 0x70,
  0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18,
  0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x32, 0x34,
  0x0a, 0x07, 0x47, 0x72, 0x65, 0x65, 0x74, 0x65, 0x72, 0x12, 0x29, 0x0a, 0x08, 0x53, 0x61, 0x79,
  0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x12, 0x0d, 0x2e, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x71,
  0x75, 0x65, 0x73, 0x74, 0x1a, 0x0e, 0x2e, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x73, 0x70,
  0x6f, 0x6e, 0x73, 0x65, 0x42, 0x1f, 0x5a, 0x1d, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63,
  0x6f, 0x6d, 0x2f, 0x78, 0x69, 0x6c, 0x75, 0x6f, 0x2f, 0x6d, 0x79, 0x72, 0x70, 0x63, 0x2f, 0x73,
  0x65, 0x72, 0x76, 0x65, 0x72, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}

var (
  file_greeter_proto_rawDescOnce sync.Once
  file_greeter_proto_rawDescData = file_greeter_proto_rawDesc
)

func file_greeter_proto_rawDescGZIP() []byte {
  file_greeter_proto_rawDescOnce.Do(func() {
    file_greeter_proto_rawDescData = protoimpl.X.CompressGZIP(file_greeter_proto_rawDescData)
  })
  return file_greeter_proto_rawDescData
}

var file_greeter_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_greeter_proto_goTypes = []interface{}{
  (*HelloRequest)(nil),  // 0: HelloRequest
  (*HelloResponse)(nil), // 1: HelloResponse
}
var file_greeter_proto_depIdxs = []int32{
  0, // 0: Greeter.SayHello:input_type -> HelloRequest
  1, // 1: Greeter.SayHello:output_type -> HelloResponse
  1, // [1:2] is the sub-list for method output_type
  0, // [0:1] is the sub-list for method input_type
  0, // [0:0] is the sub-list for extension type_name
  0, // [0:0] is the sub-list for extension extendee
  0, // [0:0] is the sub-list for field type_name
}

func init() { file_greeter_proto_init() }
func file_greeter_proto_init() {
  if File_greeter_proto != nil {
    return
  }
  if !protoimpl.UnsafeEnabled {
    file_greeter_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
      switch v := v.(*HelloRequest); i {
      case 0:
        return &v.state
      case 1:
        return &v.sizeCache
      case 2:
        return &v.unknownFields
      default:
        return nil
      }
    }
    file_greeter_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
      switch v := v.(*HelloResponse); i {
      case 0:
        return &v.state
      case 1:
        return &v.sizeCache
      case 2:
        return &v.unknownFields
      default:
        return nil
      }
    }
  }
  type x struct{}
  out := protoimpl.TypeBuilder{
    File: protoimpl.DescBuilder{
      GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
      RawDescriptor: file_greeter_proto_rawDesc,
      NumEnums:      0,
      NumMessages:   2,
      NumExtensions: 0,
      NumServices:   1,
    },
    GoTypes:           file_greeter_proto_goTypes,
    DependencyIndexes: file_greeter_proto_depIdxs,
    MessageInfos:      file_greeter_proto_msgTypes,
  }.Build()
  File_greeter_proto = out.File
  file_greeter_proto_rawDesc = nil
  file_greeter_proto_goTypes = nil
  file_greeter_proto_depIdxs = nil
}

代码:greeter_grpc.pb.go

代码语言:javascript复制
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.2.0
// - protoc             v4.23.3
// source: greeter.proto

package pb

import (
  context "context"
  grpc "google.golang.org/grpc"
  codes "google.golang.org/grpc/codes"
  status "google.golang.org/grpc/status"
)

// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.32.0 or later.
const _ = grpc.SupportPackageIsVersion7

// GreeterClient is the client API for Greeter service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type GreeterClient interface {
  SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloResponse, error)
}

type greeterClient struct {
  cc grpc.ClientConnInterface
}

func NewGreeterClient(cc grpc.ClientConnInterface) GreeterClient {
  return &greeterClient{cc}
}

func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloResponse, error) {
  out := new(HelloResponse)
  err := c.cc.Invoke(ctx, "/Greeter/SayHello", in, out, opts...)
  if err != nil {
    return nil, err
  }
  return out, nil
}

// GreeterServer is the server API for Greeter service.
// All implementations must embed UnimplementedGreeterServer
// for forward compatibility
type GreeterServer interface {
  SayHello(context.Context, *HelloRequest) (*HelloResponse, error)
  mustEmbedUnimplementedGreeterServer()
}

// UnimplementedGreeterServer must be embedded to have forward compatible implementations.
type UnimplementedGreeterServer struct {
}

func (UnimplementedGreeterServer) SayHello(context.Context, *HelloRequest) (*HelloResponse, error) {
  return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented")
}
func (UnimplementedGreeterServer) mustEmbedUnimplementedGreeterServer() {}

// UnsafeGreeterServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to GreeterServer will
// result in compilation errors.
type UnsafeGreeterServer interface {
  mustEmbedUnimplementedGreeterServer()
}

func RegisterGreeterServer(s grpc.ServiceRegistrar, srv GreeterServer) {
  s.RegisterService(&Greeter_ServiceDesc, srv)
}

func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
  in := new(HelloRequest)
  if err := dec(in); err != nil {
    return nil, err
  }
  if interceptor == nil {
    return srv.(GreeterServer).SayHello(ctx, in)
  }
  info := &grpc.UnaryServerInfo{
    Server:     srv,
    FullMethod: "/Greeter/SayHello",
  }
  handler := func(ctx context.Context, req interface{}) (interface{}, error) {
    return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest))
  }
  return interceptor(ctx, in, info, handler)
}

// Greeter_ServiceDesc is the grpc.ServiceDesc for Greeter service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Greeter_ServiceDesc = grpc.ServiceDesc{
  ServiceName: "Greeter",
  HandlerType: (*GreeterServer)(nil),
  Methods: []grpc.MethodDesc{
    {
      MethodName: "SayHello",
      Handler:    _Greeter_SayHello_Handler,
    },
  },
  Streams:  []grpc.StreamDesc{},
  Metadata: "greeter.proto",
}

三、实现 gRPC 服务

在 Go 中,实现 gRPC 服务涉及创建一个服务对象并注册到 gRPC 服务器,然后在指定端口启动这个服务器。这个服务对象是我们实现的服务接口,它定义了我们的业务逻辑。例如,我们可以这样实现 Greeter 服务:

代码语言:javascript复制
package main

import (
  context "context"
  "demo/mygrpc/pb"
  "log"
  "net"

  grpc "google.golang.org/grpc"
)

type server struct {
  // 可以在这里添加其他字段
  pb.UnimplementedGreeterServer
}

func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloResponse, error) {
  return &pb.HelloResponse{Message: "Hello "   in.Name}, nil
}

func main() {
  // 创建并启动 gRPC 服务器
  lis, err := net.Listen("tcp", ":50051")
  if err != nil {
    log.Fatalf("failed to listen: %v", err)
  }
  grpcServer := grpc.NewServer()

  // 注册服务
  greeterServer := &server{}
  pb.RegisterGreeterServer(grpcServer, greeterServer)

  // 开始接收请求
  if err := grpcServer.Serve(lis); err != nil {
    log.Fatalf("failed to serve: %v", err)
  }
}

四、创建 gRPC 客户端

在 Go 中创建一个 gRPC 客户端涉及连接到 gRPC 服务器,并通过这个连接创建一个客户端对象,这个对象提供我们服务的方法。例如,我们可以这样创建 Greeter 服务的客户端:

代码语言:javascript复制
package main

import (
  "context"
  "demo/mygrpc/pb"
  "log"
  "time"

  "google.golang.org/grpc"
)

func main() {
  conn, err := grpc.Dial(":50051", grpc.WithInsecure())
  if err != nil {
    log.Fatalf("did not connect: %v", err)
  }
  defer conn.Close()

  client := pb.NewGreeterClient(conn)

  ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  defer cancel()

  r, err := client.SayHello(ctx, &pb.HelloRequest{Name: "world"})
  if err != nil {
    log.Fatalf("could not greet: %v", err)
  }
  log.Printf("Greeting: %s", r.GetMessage())
}

运行测试:

项目结构:

代码语言:javascript复制
demomygrpcserver> go run .

demomygrpcclient> go run .
2023/07/05 22:24:50 Greeting: Hello world

结论

以上就是 gRPC 在 Go 中的基本使用方法。我们使用 Protobuf 定义了服务和消息类型,然后生成了 Go 代码,并实现了服务和客户端。需要注意的是,gRPC 有很多高级功能,比如支持多种 API 设计(一对一,一对多,多对一,多对多),拦截器,流量控制,负载均衡等等,这些都是值得深入研究的主题。

1 人点赞