gRPC教程 — 调用实例详解_c# grpc

1 项目结构

完整的项目结构

├─grpc01
│  │  go.mod
│  │  go.sum
│  │
│  ├─client
│  │  ├─client.go
│  │
│  ├─pbfile
│  │  │  hello.proto
│  │
│  └─server
│      ├─server.go
│  │
│  └─service
│      ├─hello.pb.go
│      ├─hello_grpc.pb.go
│


在这里插入图片描述

2 Protobuf

syntax = "proto3";

package service;

option go_package = '../service';

// 定义request model
message ProductRequest {
    int32 prod_id = 1; // 1代表顺序
}
// 定义response model
message ProductResponse {
    int32 prod_stock = 1; // 1代表顺序
}

// 定义服务主体
service ProdService {
    // 定义方法
    rpc GetProductStock(ProductRequest) returns(ProductResponse);
}



执行:

protoc --go\_out=. --go-grpc_out=. *.proto

然后会生成service文件夹hello.pb.gohello_grpc.pb.go
hello.pb.go:结构体相关,每个结构体都有5个相同的方法,分别是Reset()String()ProtoMessage()ProtoReflect()Descriptor()

// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v3.19.4
// source: hello.proto

package service

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)
)

// 定义request model
type ProductRequest struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	ProdId int32 `protobuf:"varint,1,opt,name=prod\_id,json=prodId,proto3" json:"prod\_id,omitempty"` // 1代表顺序
}

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

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

func (\*ProductRequest) ProtoMessage() {}

func (x \*ProductRequest) ProtoReflect() protoreflect.Message {
	mi := &file_hello_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 ProductRequest.ProtoReflect.Descriptor instead.
func (\*ProductRequest) Descriptor() ([]byte, []int) {
	return file\_hello\_proto\_rawDescGZIP(), []int{0}
}

func (x \*ProductRequest) GetProdId() int32 {
	if x != nil {
		return x.ProdId
	}
	return 0
}

// 定义response model
type ProductResponse struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	ProdStock int32 `protobuf:"varint,1,opt,name=prod\_stock,json=prodStock,proto3" json:"prod\_stock,omitempty"` // 1代表顺序
}

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

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

func (\*ProductResponse) ProtoMessage() {}

func (x \*ProductResponse) ProtoReflect() protoreflect.Message {
	mi := &file_hello_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 ProductResponse.ProtoReflect.Descriptor instead.
func (\*ProductResponse) Descriptor() ([]byte, []int) {
	return file\_hello\_proto\_rawDescGZIP(), []int{1}
}

func (x \*ProductResponse) GetProdStock() int32 {
	if x != nil {
		return x.ProdStock
	}
	return 0
}

var File_hello_proto protoreflect.FileDescriptor

var file_hello_proto_rawDesc = []byte{
	0x0a, 0x0b, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x07, 0x73,
	0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x22, 0x29, 0x0a, 0x0e, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63,
	0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x17, 0x0a, 0x07, 0x70, 0x72, 0x6f, 0x64,
	0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x06, 0x70, 0x72, 0x6f, 0x64, 0x49,
	0x64, 0x22, 0x30, 0x0a, 0x0f, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x52, 0x65, 0x73, 0x70,
	0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x70, 0x72, 0x6f, 0x64, 0x5f, 0x73, 0x74, 0x6f,
	0x63, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x09, 0x70, 0x72, 0x6f, 0x64, 0x53, 0x74,
	0x6f, 0x63, 0x6b, 0x32, 0x53, 0x0a, 0x0b, 0x50, 0x72, 0x6f, 0x64, 0x53, 0x65, 0x72, 0x76, 0x69,
	0x63, 0x65, 0x12, 0x44, 0x0a, 0x0f, 0x47, 0x65, 0x74, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74,
	0x53, 0x74, 0x6f, 0x63, 0x6b, 0x12, 0x17, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e,
	0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x18,
	0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74,
	0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x0c, 0x5a, 0x0a, 0x2e, 0x2e, 0x2f, 0x73,
	0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}

var (
	file_hello_proto_rawDescOnce sync.Once
	file_hello_proto_rawDescData = file_hello_proto_rawDesc
)

func file\_hello\_proto\_rawDescGZIP() []byte {
	file_hello_proto_rawDescOnce.Do(func() {
		file_hello_proto_rawDescData = protoimpl.X.CompressGZIP(file_hello_proto_rawDescData)
	})
	return file_hello_proto_rawDescData
}

var file_hello_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_hello_proto_goTypes = []interface{}{
	(\*ProductRequest)(nil),  // 0: service.ProductRequest
	(\*ProductResponse)(nil), // 1: service.ProductResponse
}
var file_hello_proto_depIdxs = []int32{
	0, // 0: service.ProdService.GetProductStock:input\_type -> service.ProductRequest
	1, // 1: service.ProdService.GetProductStock:output\_type -> service.ProductResponse
	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\_hello\_proto\_init() }
func file\_hello\_proto\_init() {
	if File_hello_proto != nil {
		return
	}
	if !protoimpl.UnsafeEnabled {
		file_hello_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(\*ProductRequest); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
		file_hello_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(\*ProductResponse); 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_hello_proto_rawDesc,
			NumEnums:      0,
			NumMessages:   2,
			NumExtensions: 0,
			NumServices:   1,
		},
		GoTypes:           file_hello_proto_goTypes,
		DependencyIndexes: file_hello_proto_depIdxs,
		MessageInfos:      file_hello_proto_msgTypes,
	}.Build()
	File_hello_proto = out.File
	file_hello_proto_rawDesc = nil
	file_hello_proto_goTypes = nil
	file_hello_proto_depIdxs = nil
}


hello_grpc.pb.go:rpc相关的方法,分为(Client)客户端,(Server)服务端。
Client端:有接口,结构体,建立客户端连接的方法。
Server端:有接口,结构体,方法等6个,需要注意的是服务端在使用前需要重写结构体并实现接口方法才行,否则会报错。
各个方法的末尾可以鉴别是客户端的方法还是服务端的方法。

// Code generated by protoc-gen-go-grpc. DO NOT EDIT.

package service

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

// ProdServiceClient is the client API for ProdService 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 ProdServiceClient interface {
	// 定义方法
	GetProductStock(ctx context.Context, in \*ProductRequest, opts ...grpc.CallOption) (\*ProductResponse, error)
}

type prodServiceClient struct {
	cc grpc.ClientConnInterface
}

func NewProdServiceClient(cc grpc.ClientConnInterface) ProdServiceClient {
	return &prodServiceClient{cc}
}

func (c \*prodServiceClient) GetProductStock(ctx context.Context, in \*ProductRequest, opts ...grpc.CallOption) (\*ProductResponse, error) {
	out := new(ProductResponse)
	err := c.cc.Invoke(ctx, "/service.ProdService/GetProductStock", in, out, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

// ProdServiceServer is the server API for ProdService service.
// All implementations must embed UnimplementedProdServiceServer
// for forward compatibility
type ProdServiceServer interface {
	// 定义方法
	GetProductStock(context.Context, \*ProductRequest) (\*ProductResponse, error)
	mustEmbedUnimplementedProdServiceServer()
}

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

func (UnimplementedProdServiceServer) GetProductStock(context.Context, \*ProductRequest) (\*ProductResponse, error) {
	return nil, status.Errorf(codes.Unimplemented, "method GetProductStock not implemented")
}
func (UnimplementedProdServiceServer) mustEmbedUnimplementedProdServiceServer() {}

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

func RegisterProdServiceServer(s grpc.ServiceRegistrar, srv ProdServiceServer) {
	s.RegisterService(&ProdService_ServiceDesc, srv)
}

func \_ProdService\_GetProductStock\_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(ProductRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(ProdServiceServer).GetProductStock(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/service.ProdService/GetProductStock",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(ProdServiceServer).GetProductStock(ctx, req.(\*ProductRequest))
	}
	return interceptor(ctx, in, info, handler)
}

// ProdService\_ServiceDesc is the grpc.ServiceDesc for ProdService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var ProdService_ServiceDesc = grpc.ServiceDesc{
	ServiceName: "service.ProdService",
	HandlerType: (\*ProdServiceServer)(nil),
	Methods: []grpc.MethodDesc{
		{
			MethodName: "GetProductStock",
			Handler:    _ProdService_GetProductStock_Handler,
		},
	},
	Streams:  []grpc.StreamDesc{},
	Metadata: "hello.proto",
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值