天天看点

Grpc Golang项目实践从小白到入门

Grpc Golang项目实践从小白到入门

本教程以windows作为开发环境,其他环境可以对应搜索案例,不多废话,直接上代码,原理自己百度

一、环境部署

  • golang开发环境
    自行百度,本文不做指导
               
  • protoc.exe(官网下载,例如:protoc-21.9-win64.zip),将其加入环境变量
    https://github.com/protocolbuffers/protobuf/releases
               
  • protoc-gen-go.exe和protoc-gen-go-grpc.exe
    go get github.com/golang/protobuf/protoc-gen-go
    go install github.com/golang/protobuf/protoc-gen-go
    或者:
    go install google.golang.org/protobuf/cmd/protoc-gen-go
    go install google.golang.org/grpc/cmd/protoc-gen-go-grpc
    执行后去golang的安装路径的/bin找到protoc-gen-go.exe,protoc-gen-go-grpc.exe,加入环境变量
               

二、创建Golang工程

  • 项目简介
    • 功能: 创建一个grpc服务,实现客户端向服务端注册,并且返回客户端uuid,打印客户端信息,对应应用场景为远程过程的服务调用中的开始阶段:客户端注册
    • 涉及模块
      • 服务端
      • 客户端
      • 公共交互模块
    • 项目结构
      目录结构:
      E:\WORKSPACE\GO\SRPC
      ├─.idea
      ├─client
      │  └─client.go // 客户端
      ├─common // 公共目录
      │  └─client.proto // proto文件
      │  └─client
      │     └─client_pb.go 
      │     └─client_grpc.pb.go // grpc服务
      └─server
      │     └─server.go // 服务端
                 

三、编写proto协议并生成对应的go程序

  • client.proto文件
    syntax = "proto3";
    option go_package="/client";
    package client;
    
    
    service Client {
      rpc registerClient(ClientMsg) returns (ClientID); // 客户端注册
      rpc getClient(ClientID) returns (ClientMsg); // 根据注册所得UUID获取注册信息
    }
    
    message ClientMsg {
      string id = 1; // 自增id
      string name = 2; // 客户端名称
      string description = 3; // 客户端描述
      float uuid = 4; // 客户端uuid
    }
    
    message ClientID { // 客户端uuid
      string value = 1;
    }
               
  • client_pb.go 、client_grpc.pb.go生成
    cd common/ //进入common目录
    // 统一生成
    protoc --go_out=./ --go-grpc_out=./ client.proto
    // 单独生成
    protoc --go_out=./ client.proto
    protoc --go-grpc_out=./ client.proto
               
    client_pb.go
    // Code generated by protoc-gen-go. DO NOT EDIT.
    // versions:
    // 	protoc-gen-go v1.28.1
    // 	protoc        v3.21.9
    // source: client.proto
    
    package client
    
    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 ClientMsg struct {
    	state         protoimpl.MessageState
    	sizeCache     protoimpl.SizeCache
    	unknownFields protoimpl.UnknownFields
    
    	Id          string  `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
    	Name        string  `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
    	Description string  `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"`
    	Uuid        float32 `protobuf:"fixed32,4,opt,name=uuid,proto3" json:"uuid,omitempty"`
    }
    
    func (x *ClientMsg) Reset() {
    	*x = ClientMsg{}
    	if protoimpl.UnsafeEnabled {
    		mi := &file_client_proto_msgTypes[0]
    		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
    		ms.StoreMessageInfo(mi)
    	}
    }
    
    func (x *ClientMsg) String() string {
    	return protoimpl.X.MessageStringOf(x)
    }
    
    func (*ClientMsg) ProtoMessage() {}
    
    func (x *ClientMsg) ProtoReflect() protoreflect.Message {
    	mi := &file_client_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 ClientMsg.ProtoReflect.Descriptor instead.
    func (*ClientMsg) Descriptor() ([]byte, []int) {
    	return file_client_proto_rawDescGZIP(), []int{0}
    }
    
    func (x *ClientMsg) GetId() string {
    	if x != nil {
    		return x.Id
    	}
    	return ""
    }
    
    func (x *ClientMsg) GetName() string {
    	if x != nil {
    		return x.Name
    	}
    	return ""
    }
    
    func (x *ClientMsg) GetDescription() string {
    	if x != nil {
    		return x.Description
    	}
    	return ""
    }
    
    func (x *ClientMsg) GetUuid() float32 {
    	if x != nil {
    		return x.Uuid
    	}
    	return 0
    }
    
    type ClientID struct {
    	state         protoimpl.MessageState
    	sizeCache     protoimpl.SizeCache
    	unknownFields protoimpl.UnknownFields
    
    	Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
    }
    
    func (x *ClientID) Reset() {
    	*x = ClientID{}
    	if protoimpl.UnsafeEnabled {
    		mi := &file_client_proto_msgTypes[1]
    		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
    		ms.StoreMessageInfo(mi)
    	}
    }
    
    func (x *ClientID) String() string {
    	return protoimpl.X.MessageStringOf(x)
    }
    
    func (*ClientID) ProtoMessage() {}
    
    func (x *ClientID) ProtoReflect() protoreflect.Message {
    	mi := &file_client_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 ClientID.ProtoReflect.Descriptor instead.
    func (*ClientID) Descriptor() ([]byte, []int) {
    	return file_client_proto_rawDescGZIP(), []int{1}
    }
    
    func (x *ClientID) GetValue() string {
    	if x != nil {
    		return x.Value
    	}
    	return ""
    }
    
    var File_client_proto protoreflect.FileDescriptor
    
    var file_client_proto_rawDesc = []byte{
    	0x0a, 0x0c, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x06,
    	0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x22, 0x65, 0x0a, 0x09, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74,
    	0x4d, 0x73, 0x67, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52,
    	0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28,
    	0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72,
    	0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65,
    	0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x12, 0x0a, 0x04, 0x75, 0x75, 0x69,
    	0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x02, 0x52, 0x04, 0x75, 0x75, 0x69, 0x64, 0x22, 0x20, 0x0a,
    	0x08, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x49, 0x44, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c,
    	0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x32,
    	0x71, 0x0a, 0x06, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x12, 0x35, 0x0a, 0x0e, 0x72, 0x65, 0x67,
    	0x69, 0x73, 0x74, 0x65, 0x72, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x12, 0x11, 0x2e, 0x63, 0x6c,
    	0x69, 0x65, 0x6e, 0x74, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x4d, 0x73, 0x67, 0x1a, 0x10,
    	0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x49, 0x44,
    	0x12, 0x30, 0x0a, 0x09, 0x67, 0x65, 0x74, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x12, 0x10, 0x2e,
    	0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x49, 0x44, 0x1a,
    	0x11, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x4d,
    	0x73, 0x67, 0x42, 0x09, 0x5a, 0x07, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x62, 0x06, 0x70,
    	0x72, 0x6f, 0x74, 0x6f, 0x33,
    }
    
    var (
    	file_client_proto_rawDescOnce sync.Once
    	file_client_proto_rawDescData = file_client_proto_rawDesc
    )
    
    func file_client_proto_rawDescGZIP() []byte {
    	file_client_proto_rawDescOnce.Do(func() {
    		file_client_proto_rawDescData = protoimpl.X.CompressGZIP(file_client_proto_rawDescData)
    	})
    	return file_client_proto_rawDescData
    }
    
    var file_client_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
    var file_client_proto_goTypes = []interface{}{
    	(*ClientMsg)(nil), // 0: client.ClientMsg
    	(*ClientID)(nil),  // 1: client.ClientID
    }
    var file_client_proto_depIdxs = []int32{
    	0, // 0: client.Client.registerClient:input_type -> client.ClientMsg
    	1, // 1: client.Client.getClient:input_type -> client.ClientID
    	1, // 2: client.Client.registerClient:output_type -> client.ClientID
    	0, // 3: client.Client.getClient:output_type -> client.ClientMsg
    	2, // [2:4] is the sub-list for method output_type
    	0, // [0:2] 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_client_proto_init() }
    func file_client_proto_init() {
    	if File_client_proto != nil {
    		return
    	}
    	if !protoimpl.UnsafeEnabled {
    		file_client_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
    			switch v := v.(*ClientMsg); i {
    			case 0:
    				return &v.state
    			case 1:
    				return &v.sizeCache
    			case 2:
    				return &v.unknownFields
    			default:
    				return nil
    			}
    		}
    		file_client_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
    			switch v := v.(*ClientID); 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_client_proto_rawDesc,
    			NumEnums:      0,
    			NumMessages:   2,
    			NumExtensions: 0,
    			NumServices:   1,
    		},
    		GoTypes:           file_client_proto_goTypes,
    		DependencyIndexes: file_client_proto_depIdxs,
    		MessageInfos:      file_client_proto_msgTypes,
    	}.Build()
    	File_client_proto = out.File
    	file_client_proto_rawDesc = nil
    	file_client_proto_goTypes = nil
    	file_client_proto_depIdxs = nil
    }
    
               
    client_grpc.pb.go
    // Code generated by protoc-gen-go-grpc. DO NOT EDIT.
    // versions:
    // - protoc-gen-go-grpc v1.2.0
    // - protoc             v3.21.9
    // source: client.proto
    
    package client
    
    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
    
    // ClientClient is the client API for Client 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 ClientClient interface {
    	RegisterClient(ctx context.Context, in *ClientMsg, opts ...grpc.CallOption) (*ClientID, error)
    	GetClient(ctx context.Context, in *ClientID, opts ...grpc.CallOption) (*ClientMsg, error)
    }
    
    type clientClient struct {
    	cc grpc.ClientConnInterface
    }
    
    func NewClientClient(cc grpc.ClientConnInterface) ClientClient {
    	return &clientClient{cc}
    }
    
    func (c *clientClient) RegisterClient(ctx context.Context, in *ClientMsg, opts ...grpc.CallOption) (*ClientID, error) {
    	out := new(ClientID)
    	err := c.cc.Invoke(ctx, "/client.Client/registerClient", in, out, opts...)
    	if err != nil {
    		return nil, err
    	}
    	return out, nil
    }
    
    func (c *clientClient) GetClient(ctx context.Context, in *ClientID, opts ...grpc.CallOption) (*ClientMsg, error) {
    	out := new(ClientMsg)
    	err := c.cc.Invoke(ctx, "/client.Client/getClient", in, out, opts...)
    	if err != nil {
    		return nil, err
    	}
    	return out, nil
    }
    
    // ClientServer is the server API for Client service.
    // All implementations should embed UnimplementedClientServer
    // for forward compatibility
    type ClientServer interface {
    	RegisterClient(context.Context, *ClientMsg) (*ClientID, error)
    	GetClient(context.Context, *ClientID) (*ClientMsg, error)
    }
    
    // UnimplementedClientServer should be embedded to have forward compatible implementations.
    type UnimplementedClientServer struct {
    }
    
    func (UnimplementedClientServer) RegisterClient(context.Context, *ClientMsg) (*ClientID, error) {
    	return nil, status.Errorf(codes.Unimplemented, "method RegisterClient not implemented")
    }
    func (UnimplementedClientServer) GetClient(context.Context, *ClientID) (*ClientMsg, error) {
    	return nil, status.Errorf(codes.Unimplemented, "method GetClient not implemented")
    }
    
    // UnsafeClientServer may be embedded to opt out of forward compatibility for this service.
    // Use of this interface is not recommended, as added methods to ClientServer will
    // result in compilation errors.
    type UnsafeClientServer interface {
    	mustEmbedUnimplementedClientServer()
    }
    
    func RegisterClientServer(s grpc.ServiceRegistrar, srv ClientServer) {
    	s.RegisterService(&Client_ServiceDesc, srv)
    }
    
    func _Client_RegisterClient_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
    	in := new(ClientMsg)
    	if err := dec(in); err != nil {
    		return nil, err
    	}
    	if interceptor == nil {
    		return srv.(ClientServer).RegisterClient(ctx, in)
    	}
    	info := &grpc.UnaryServerInfo{
    		Server:     srv,
    		FullMethod: "/client.Client/registerClient",
    	}
    	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
    		return srv.(ClientServer).RegisterClient(ctx, req.(*ClientMsg))
    	}
    	return interceptor(ctx, in, info, handler)
    }
    
    func _Client_GetClient_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
    	in := new(ClientID)
    	if err := dec(in); err != nil {
    		return nil, err
    	}
    	if interceptor == nil {
    		return srv.(ClientServer).GetClient(ctx, in)
    	}
    	info := &grpc.UnaryServerInfo{
    		Server:     srv,
    		FullMethod: "/client.Client/getClient",
    	}
    	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
    		return srv.(ClientServer).GetClient(ctx, req.(*ClientID))
    	}
    	return interceptor(ctx, in, info, handler)
    }
    
    // Client_ServiceDesc is the grpc.ServiceDesc for Client service.
    // It's only intended for direct use with grpc.RegisterService,
    // and not to be introspected or modified (even as a copy)
    var Client_ServiceDesc = grpc.ServiceDesc{
    	ServiceName: "client.Client",
    	HandlerType: (*ClientServer)(nil),
    	Methods: []grpc.MethodDesc{
    		{
    			MethodName: "registerClient",
    			Handler:    _Client_RegisterClient_Handler,
    		},
    		{
    			MethodName: "getClient",
    			Handler:    _Client_GetClient_Handler,
    		},
    	},
    	Streams:  []grpc.StreamDesc{},
    	Metadata: "client.proto",
    }
    
               
  • 新版踩坑注意
    • 私有接口方法的继承:mustEmbedUnimplementedXXXServer的问题,server端容易报错
    • 解决方法
      1. 在grpc server实现结构体中匿名嵌入Unimplemented***Server结构体
      2. 使用protoc生成server代码时命令行加上关闭选项,

        protoc --go-grpc_out=require_unimplemented_servers=false

        参考:https://github.com/grpc/grpc-go/blob/master/cmd/protoc-gen-go-grpc/README.md

      1. 关闭私有接口方法的继承:mustEmbedUnimplementedXXXServer
      protoc --go-grpc_out=./ --go-grpc_opt=require_unimplemented_servers=false client.proto
      2. 指定当前目录,使得proto的go_package配置不生效: 推荐使用
      protoc --go-grpc_out=./ --go-grpc_opt=require_unimplemented_servers=false --go-grpc_opt=paths=source_relative client.proto
                 

四、编写客户端

package main

import (
	"context"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"time"

	"google.golang.org/grpc"
	pb "srpc/common/client"
)

const (
	address = "localhost:50052"
)

func main() {
	// Set up a connection to the server.
	conn, err := grpc.Dial(address, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	c := pb.NewClientClient(conn)

	// Contact the server and print out its response.
	name := "proto agent"
	description := "test grpc conn."
	uid:= float32(699.00)
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	r, err := c.RegisterClient(ctx, &pb.ClientMsg{Name: name, Description: description, Uuid: uid})
	if err != nil {
		log.Fatalf("Client: Could not register Client: %v", err)
	}
	log.Printf("Client: ID %s register successfully", r.Value)

	product, err := c.GetClient(ctx, &pb.ClientID{Value: r.Value})
	if err != nil {
		log.Fatalf("Client: Could not get client: %v", err)
	}
	log.Printf("Client: %v", product.String())
}

           

五、编写服务端

package main

import (
	"context"
	"log"
	"net"
	pb "srpc/common/client"

	"github.com/gofrs/uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

const (
	port = ":50052"
)

// server is used to implement ecommerce/product_info.
type server struct {
	clientMap map[string]*pb.ClientMsg
}

// RegisterClient implements ecommerce.AddProduct
func (s *server) RegisterClient(ctx context.Context,
	in *pb.ClientMsg) (*pb.ClientID, error) {
	out, err := uuid.NewV4()
	if err != nil {
		return nil, status.Errorf(codes.Internal, "Error while generating Client ID", err)
	}
	in.Id = out.String()
	if s.clientMap == nil {
		s.clientMap = make(map[string]*pb.ClientMsg)
	}
	s.clientMap[in.Id] = in
	log.Printf("Server: client %v : %v - Register.", in.Id, in.Name)
	return &pb.ClientID{Value: in.Id}, status.New(codes.OK, "").Err()
}

// GetClient implements ecommerce.GetProduct
func (s *server) GetClient(ctx context.Context, in *pb.ClientID) (*pb.ClientMsg, error) {
	product, exists := s.clientMap[in.Value]
	if exists && product != nil {
		log.Printf("Server: client %v : %v - Retrieved.", product.Id, product.Name)
		return product, status.New(codes.OK, "").Err()
	}
	return nil, status.Errorf(codes.NotFound, "Client does not exist.", in.Value)
}

func main() {
	lis, err := net.Listen("tcp", port)
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	pb.RegisterClientServer(s, &server{})
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}

           

六、运行

  • 服务端
    2022/11/24 18:58:38 Server: client 6f58ad7b-b61d-43f1-a2a5-7cea69886765 : proto agent - Register.
    2022/11/24 18:58:38 Server: client 6f58ad7b-b61d-43f1-a2a5-7cea69886765 : proto agent - Retrieved.
               
  • 客户端
    2022/11/24 18:58:38 Client: ID 6f58ad7b-b61d-43f1-a2a5-7cea69886765 register successfully
    2022/11/24 18:58:38 Client: id:"6f58ad7b-b61d-43f1-a2a5-7cea69886765" name:"proto agent" description:"test grpc conn." uuid:699
               

继续阅读