From e3af30df41a1feb68588eec83b81e289b0d70b5b Mon Sep 17 00:00:00 2001 From: guoqiang Date: Sun, 3 Dec 2023 14:23:37 +0800 Subject: [PATCH] =?UTF-8?q?calculator-grpc=E6=B5=81=E6=A8=A1=E5=BC=8F?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 12 +- calculator/client/Average.go | 46 +++ calculator/client/Sum.go | 46 +++ calculator/client/main.go | 26 ++ calculator/pb/calculator.pb.go | 475 ++++++++++++++++++++++++++++ calculator/pb/calculator_grpc.pb.go | 282 +++++++++++++++++ calculator/proto/calculator.proto | 40 +++ calculator/server/Average.go | 34 ++ calculator/server/RandomNums.go | 29 ++ calculator/server/Sum.go | 33 ++ calculator/server/main.go | 38 +++ go.mod | 1 + go.sum | 9 + 13 files changed, 1070 insertions(+), 1 deletion(-) create mode 100644 calculator/client/Average.go create mode 100644 calculator/client/Sum.go create mode 100644 calculator/client/main.go create mode 100644 calculator/pb/calculator.pb.go create mode 100644 calculator/pb/calculator_grpc.pb.go create mode 100644 calculator/proto/calculator.proto create mode 100644 calculator/server/Average.go create mode 100644 calculator/server/RandomNums.go create mode 100644 calculator/server/Sum.go create mode 100644 calculator/server/main.go diff --git a/Makefile b/Makefile index 5e4e79f..2ac8f8a 100644 --- a/Makefile +++ b/Makefile @@ -14,5 +14,15 @@ greet-evans: greet-evans-reflect: evans -r repl --port 5632 -.PHONY: tidy greet-gen greet-build greet-evans greet-evans-reflect +calculator-gen: + protoc -Icalculator/proto/ --go_out=./calculator --go_opt=module=git.gqnotes.com/guoqiang/grpcexercises/calculator --go-grpc_out=./calculator --go-grpc_opt=module=git.gqnotes.com/guoqiang/grpcexercises/calculator calculator/proto/*.proto + +calculator-build: + go build -o ./calculator/bin/server-osx ./calculator/server + go build -o ./calculator/bin/client-osx ./calculator/client + + calculator-evans-reflect: + evans -r repl --port 5633 + +.PHONY: tidy greet-gen greet-build greet-evans greet-evans-reflect calculator-gen calculator-build calculator-evans-reflect diff --git a/calculator/client/Average.go b/calculator/client/Average.go new file mode 100644 index 0000000..66a5dd5 --- /dev/null +++ b/calculator/client/Average.go @@ -0,0 +1,46 @@ +package main + +import ( + "context" + "git.gqnotes.com/guoqiang/grpcexercises/calculator/pb" + "log" +) + +// Average 计算平均数-双向流式 +func Average(client pb.CalculateServiceClient) { + // 构造数据 + nums := []int64{1, 2, 3, 4, 5} + + avClient, err := client.Average(context.Background()) + + if err != nil { + return + } + + // 发送数据 + for _, num := range nums { + err = avClient.Send(&pb.AverageRequest{ + Num: num, + }) + + if err != nil { + return + } + + recv, err := avClient.Recv() + + if err != nil { + return + } + + log.Printf("num:%+v\trecv:%+v\n", num, recv) + } + + // 关闭连接 + err = avClient.CloseSend() + + if err != nil { + log.Fatalf("failed to close: %v", err) + return + } +} diff --git a/calculator/client/Sum.go b/calculator/client/Sum.go new file mode 100644 index 0000000..5c11255 --- /dev/null +++ b/calculator/client/Sum.go @@ -0,0 +1,46 @@ +package main + +import ( + "context" + "git.gqnotes.com/guoqiang/grpcexercises/calculator/pb" + "io" + "log" +) + +// Sum 计算和-客户端流式 +func Sum(client pb.CalculateServiceClient) { + // 构造一个切片 + nums := []int64{1, 2, 3, 4, 5} + + stream, err := client.Sum(context.Background()) + + if err != nil { + log.Fatalf("failed to call: %v", err) + return + } + + // 发送数据 + for i := 0; i < len(nums); i++ { + err = stream.Send(&pb.SumRequest{ + Num: nums[i], + }) + + if err == io.EOF { + break + } + + if err != nil { + log.Fatalf("failed to send: %v", err) + return + } + } + + // 接收数据 + resp, err := stream.CloseAndRecv() + + if err != nil { + log.Fatalf("failed to recv: %v", err) + } + + log.Printf("nums:%+v\tresp:%+v\n", nums, resp) +} diff --git a/calculator/client/main.go b/calculator/client/main.go new file mode 100644 index 0000000..818ac5c --- /dev/null +++ b/calculator/client/main.go @@ -0,0 +1,26 @@ +package main + +import ( + "git.gqnotes.com/guoqiang/grpcexercises/calculator/pb" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "log" +) + +func main() { + conn, err := grpc.Dial(":5633", grpc.WithTransportCredentials(insecure.NewCredentials())) + + if err != nil { + log.Fatalf("failed to dial: %v", err) + return + } + + defer conn.Close() + + // 实例化客户端 + client := pb.NewCalculateServiceClient(conn) + + Sum(client) + + Average(client) +} diff --git a/calculator/pb/calculator.pb.go b/calculator/pb/calculator.pb.go new file mode 100644 index 0000000..e2480f4 --- /dev/null +++ b/calculator/pb/calculator.pb.go @@ -0,0 +1,475 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.31.0 +// protoc v4.25.1 +// source: calculator.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 SumRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Num int64 `protobuf:"varint,1,opt,name=num,proto3" json:"num,omitempty"` +} + +func (x *SumRequest) Reset() { + *x = SumRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_calculator_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SumRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SumRequest) ProtoMessage() {} + +func (x *SumRequest) ProtoReflect() protoreflect.Message { + mi := &file_calculator_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 SumRequest.ProtoReflect.Descriptor instead. +func (*SumRequest) Descriptor() ([]byte, []int) { + return file_calculator_proto_rawDescGZIP(), []int{0} +} + +func (x *SumRequest) GetNum() int64 { + if x != nil { + return x.Num + } + return 0 +} + +type SumResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Total int64 `protobuf:"varint,1,opt,name=total,proto3" json:"total,omitempty"` +} + +func (x *SumResponse) Reset() { + *x = SumResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_calculator_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SumResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SumResponse) ProtoMessage() {} + +func (x *SumResponse) ProtoReflect() protoreflect.Message { + mi := &file_calculator_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 SumResponse.ProtoReflect.Descriptor instead. +func (*SumResponse) Descriptor() ([]byte, []int) { + return file_calculator_proto_rawDescGZIP(), []int{1} +} + +func (x *SumResponse) GetTotal() int64 { + if x != nil { + return x.Total + } + return 0 +} + +type RandomNumsRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Num int64 `protobuf:"varint,1,opt,name=num,proto3" json:"num,omitempty"` +} + +func (x *RandomNumsRequest) Reset() { + *x = RandomNumsRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_calculator_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *RandomNumsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RandomNumsRequest) ProtoMessage() {} + +func (x *RandomNumsRequest) ProtoReflect() protoreflect.Message { + mi := &file_calculator_proto_msgTypes[2] + 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 RandomNumsRequest.ProtoReflect.Descriptor instead. +func (*RandomNumsRequest) Descriptor() ([]byte, []int) { + return file_calculator_proto_rawDescGZIP(), []int{2} +} + +func (x *RandomNumsRequest) GetNum() int64 { + if x != nil { + return x.Num + } + return 0 +} + +type RandomNumsResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Num int64 `protobuf:"varint,1,opt,name=num,proto3" json:"num,omitempty"` +} + +func (x *RandomNumsResponse) Reset() { + *x = RandomNumsResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_calculator_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *RandomNumsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RandomNumsResponse) ProtoMessage() {} + +func (x *RandomNumsResponse) ProtoReflect() protoreflect.Message { + mi := &file_calculator_proto_msgTypes[3] + 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 RandomNumsResponse.ProtoReflect.Descriptor instead. +func (*RandomNumsResponse) Descriptor() ([]byte, []int) { + return file_calculator_proto_rawDescGZIP(), []int{3} +} + +func (x *RandomNumsResponse) GetNum() int64 { + if x != nil { + return x.Num + } + return 0 +} + +type AverageRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Num int64 `protobuf:"varint,1,opt,name=num,proto3" json:"num,omitempty"` +} + +func (x *AverageRequest) Reset() { + *x = AverageRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_calculator_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *AverageRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AverageRequest) ProtoMessage() {} + +func (x *AverageRequest) ProtoReflect() protoreflect.Message { + mi := &file_calculator_proto_msgTypes[4] + 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 AverageRequest.ProtoReflect.Descriptor instead. +func (*AverageRequest) Descriptor() ([]byte, []int) { + return file_calculator_proto_rawDescGZIP(), []int{4} +} + +func (x *AverageRequest) GetNum() int64 { + if x != nil { + return x.Num + } + return 0 +} + +type AverageResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Average float32 `protobuf:"fixed32,1,opt,name=average,proto3" json:"average,omitempty"` +} + +func (x *AverageResponse) Reset() { + *x = AverageResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_calculator_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *AverageResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AverageResponse) ProtoMessage() {} + +func (x *AverageResponse) ProtoReflect() protoreflect.Message { + mi := &file_calculator_proto_msgTypes[5] + 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 AverageResponse.ProtoReflect.Descriptor instead. +func (*AverageResponse) Descriptor() ([]byte, []int) { + return file_calculator_proto_rawDescGZIP(), []int{5} +} + +func (x *AverageResponse) GetAverage() float32 { + if x != nil { + return x.Average + } + return 0 +} + +var File_calculator_proto protoreflect.FileDescriptor + +var file_calculator_proto_rawDesc = []byte{ + 0x0a, 0x10, 0x63, 0x61, 0x6c, 0x63, 0x75, 0x6c, 0x61, 0x74, 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x12, 0x05, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x1e, 0x0a, 0x0a, 0x53, 0x75, 0x6d, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x10, 0x0a, 0x03, 0x6e, 0x75, 0x6d, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x03, 0x52, 0x03, 0x6e, 0x75, 0x6d, 0x22, 0x23, 0x0a, 0x0b, 0x53, 0x75, 0x6d, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, 0x74, 0x61, + 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x22, 0x25, + 0x0a, 0x11, 0x52, 0x61, 0x6e, 0x64, 0x6f, 0x6d, 0x4e, 0x75, 0x6d, 0x73, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x12, 0x10, 0x0a, 0x03, 0x6e, 0x75, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, + 0x52, 0x03, 0x6e, 0x75, 0x6d, 0x22, 0x26, 0x0a, 0x12, 0x52, 0x61, 0x6e, 0x64, 0x6f, 0x6d, 0x4e, + 0x75, 0x6d, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x6e, + 0x75, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x03, 0x6e, 0x75, 0x6d, 0x22, 0x22, 0x0a, + 0x0e, 0x41, 0x76, 0x65, 0x72, 0x61, 0x67, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, + 0x10, 0x0a, 0x03, 0x6e, 0x75, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x03, 0x6e, 0x75, + 0x6d, 0x22, 0x2b, 0x0a, 0x0f, 0x41, 0x76, 0x65, 0x72, 0x61, 0x67, 0x65, 0x52, 0x65, 0x73, 0x70, + 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x76, 0x65, 0x72, 0x61, 0x67, 0x65, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x02, 0x52, 0x07, 0x61, 0x76, 0x65, 0x72, 0x61, 0x67, 0x65, 0x32, 0xcb, + 0x01, 0x0a, 0x10, 0x43, 0x61, 0x6c, 0x63, 0x75, 0x6c, 0x61, 0x74, 0x65, 0x53, 0x65, 0x72, 0x76, + 0x69, 0x63, 0x65, 0x12, 0x30, 0x0a, 0x03, 0x53, 0x75, 0x6d, 0x12, 0x11, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x2e, 0x53, 0x75, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x12, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x53, 0x75, 0x6d, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x22, 0x00, 0x28, 0x01, 0x12, 0x45, 0x0a, 0x0a, 0x52, 0x61, 0x6e, 0x64, 0x6f, 0x6d, 0x4e, + 0x75, 0x6d, 0x73, 0x12, 0x18, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x52, 0x61, 0x6e, 0x64, + 0x6f, 0x6d, 0x4e, 0x75, 0x6d, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x19, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x52, 0x61, 0x6e, 0x64, 0x6f, 0x6d, 0x4e, 0x75, 0x6d, 0x73, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x30, 0x01, 0x12, 0x3e, 0x0a, 0x07, + 0x41, 0x76, 0x65, 0x72, 0x61, 0x67, 0x65, 0x12, 0x15, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, + 0x41, 0x76, 0x65, 0x72, 0x61, 0x67, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x41, 0x76, 0x65, 0x72, 0x61, 0x67, 0x65, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x28, 0x01, 0x30, 0x01, 0x42, 0x36, 0x5a, 0x34, + 0x67, 0x69, 0x74, 0x2e, 0x67, 0x71, 0x6e, 0x6f, 0x74, 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, + 0x67, 0x75, 0x6f, 0x71, 0x69, 0x61, 0x6e, 0x67, 0x2f, 0x67, 0x72, 0x70, 0x63, 0x65, 0x78, 0x65, + 0x72, 0x63, 0x69, 0x73, 0x65, 0x73, 0x2f, 0x63, 0x61, 0x6c, 0x63, 0x75, 0x6c, 0x61, 0x74, 0x6f, + 0x72, 0x2f, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_calculator_proto_rawDescOnce sync.Once + file_calculator_proto_rawDescData = file_calculator_proto_rawDesc +) + +func file_calculator_proto_rawDescGZIP() []byte { + file_calculator_proto_rawDescOnce.Do(func() { + file_calculator_proto_rawDescData = protoimpl.X.CompressGZIP(file_calculator_proto_rawDescData) + }) + return file_calculator_proto_rawDescData +} + +var file_calculator_proto_msgTypes = make([]protoimpl.MessageInfo, 6) +var file_calculator_proto_goTypes = []interface{}{ + (*SumRequest)(nil), // 0: proto.SumRequest + (*SumResponse)(nil), // 1: proto.SumResponse + (*RandomNumsRequest)(nil), // 2: proto.RandomNumsRequest + (*RandomNumsResponse)(nil), // 3: proto.RandomNumsResponse + (*AverageRequest)(nil), // 4: proto.AverageRequest + (*AverageResponse)(nil), // 5: proto.AverageResponse +} +var file_calculator_proto_depIdxs = []int32{ + 0, // 0: proto.CalculateService.Sum:input_type -> proto.SumRequest + 2, // 1: proto.CalculateService.RandomNums:input_type -> proto.RandomNumsRequest + 4, // 2: proto.CalculateService.Average:input_type -> proto.AverageRequest + 1, // 3: proto.CalculateService.Sum:output_type -> proto.SumResponse + 3, // 4: proto.CalculateService.RandomNums:output_type -> proto.RandomNumsResponse + 5, // 5: proto.CalculateService.Average:output_type -> proto.AverageResponse + 3, // [3:6] is the sub-list for method output_type + 0, // [0:3] 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_calculator_proto_init() } +func file_calculator_proto_init() { + if File_calculator_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_calculator_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*SumRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_calculator_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*SumResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_calculator_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*RandomNumsRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_calculator_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*RandomNumsResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_calculator_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*AverageRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_calculator_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*AverageResponse); 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_calculator_proto_rawDesc, + NumEnums: 0, + NumMessages: 6, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_calculator_proto_goTypes, + DependencyIndexes: file_calculator_proto_depIdxs, + MessageInfos: file_calculator_proto_msgTypes, + }.Build() + File_calculator_proto = out.File + file_calculator_proto_rawDesc = nil + file_calculator_proto_goTypes = nil + file_calculator_proto_depIdxs = nil +} diff --git a/calculator/pb/calculator_grpc.pb.go b/calculator/pb/calculator_grpc.pb.go new file mode 100644 index 0000000..7ac66fe --- /dev/null +++ b/calculator/pb/calculator_grpc.pb.go @@ -0,0 +1,282 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.3.0 +// - protoc v4.25.1 +// source: calculator.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 + +const ( + CalculateService_Sum_FullMethodName = "/proto.CalculateService/Sum" + CalculateService_RandomNums_FullMethodName = "/proto.CalculateService/RandomNums" + CalculateService_Average_FullMethodName = "/proto.CalculateService/Average" +) + +// CalculateServiceClient is the client API for CalculateService 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 CalculateServiceClient interface { + // 求和-客户端流式 + Sum(ctx context.Context, opts ...grpc.CallOption) (CalculateService_SumClient, error) + // 生成一定数量的随机数-服务端流式 + RandomNums(ctx context.Context, in *RandomNumsRequest, opts ...grpc.CallOption) (CalculateService_RandomNumsClient, error) + // 双向流式求平均值 + Average(ctx context.Context, opts ...grpc.CallOption) (CalculateService_AverageClient, error) +} + +type calculateServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewCalculateServiceClient(cc grpc.ClientConnInterface) CalculateServiceClient { + return &calculateServiceClient{cc} +} + +func (c *calculateServiceClient) Sum(ctx context.Context, opts ...grpc.CallOption) (CalculateService_SumClient, error) { + stream, err := c.cc.NewStream(ctx, &CalculateService_ServiceDesc.Streams[0], CalculateService_Sum_FullMethodName, opts...) + if err != nil { + return nil, err + } + x := &calculateServiceSumClient{stream} + return x, nil +} + +type CalculateService_SumClient interface { + Send(*SumRequest) error + CloseAndRecv() (*SumResponse, error) + grpc.ClientStream +} + +type calculateServiceSumClient struct { + grpc.ClientStream +} + +func (x *calculateServiceSumClient) Send(m *SumRequest) error { + return x.ClientStream.SendMsg(m) +} + +func (x *calculateServiceSumClient) CloseAndRecv() (*SumResponse, error) { + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + m := new(SumResponse) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +func (c *calculateServiceClient) RandomNums(ctx context.Context, in *RandomNumsRequest, opts ...grpc.CallOption) (CalculateService_RandomNumsClient, error) { + stream, err := c.cc.NewStream(ctx, &CalculateService_ServiceDesc.Streams[1], CalculateService_RandomNums_FullMethodName, opts...) + if err != nil { + return nil, err + } + x := &calculateServiceRandomNumsClient{stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +type CalculateService_RandomNumsClient interface { + Recv() (*RandomNumsResponse, error) + grpc.ClientStream +} + +type calculateServiceRandomNumsClient struct { + grpc.ClientStream +} + +func (x *calculateServiceRandomNumsClient) Recv() (*RandomNumsResponse, error) { + m := new(RandomNumsResponse) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +func (c *calculateServiceClient) Average(ctx context.Context, opts ...grpc.CallOption) (CalculateService_AverageClient, error) { + stream, err := c.cc.NewStream(ctx, &CalculateService_ServiceDesc.Streams[2], CalculateService_Average_FullMethodName, opts...) + if err != nil { + return nil, err + } + x := &calculateServiceAverageClient{stream} + return x, nil +} + +type CalculateService_AverageClient interface { + Send(*AverageRequest) error + Recv() (*AverageResponse, error) + grpc.ClientStream +} + +type calculateServiceAverageClient struct { + grpc.ClientStream +} + +func (x *calculateServiceAverageClient) Send(m *AverageRequest) error { + return x.ClientStream.SendMsg(m) +} + +func (x *calculateServiceAverageClient) Recv() (*AverageResponse, error) { + m := new(AverageResponse) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +// CalculateServiceServer is the server API for CalculateService service. +// All implementations must embed UnimplementedCalculateServiceServer +// for forward compatibility +type CalculateServiceServer interface { + // 求和-客户端流式 + Sum(CalculateService_SumServer) error + // 生成一定数量的随机数-服务端流式 + RandomNums(*RandomNumsRequest, CalculateService_RandomNumsServer) error + // 双向流式求平均值 + Average(CalculateService_AverageServer) error + mustEmbedUnimplementedCalculateServiceServer() +} + +// UnimplementedCalculateServiceServer must be embedded to have forward compatible implementations. +type UnimplementedCalculateServiceServer struct { +} + +func (UnimplementedCalculateServiceServer) Sum(CalculateService_SumServer) error { + return status.Errorf(codes.Unimplemented, "method Sum not implemented") +} +func (UnimplementedCalculateServiceServer) RandomNums(*RandomNumsRequest, CalculateService_RandomNumsServer) error { + return status.Errorf(codes.Unimplemented, "method RandomNums not implemented") +} +func (UnimplementedCalculateServiceServer) Average(CalculateService_AverageServer) error { + return status.Errorf(codes.Unimplemented, "method Average not implemented") +} +func (UnimplementedCalculateServiceServer) mustEmbedUnimplementedCalculateServiceServer() {} + +// UnsafeCalculateServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to CalculateServiceServer will +// result in compilation errors. +type UnsafeCalculateServiceServer interface { + mustEmbedUnimplementedCalculateServiceServer() +} + +func RegisterCalculateServiceServer(s grpc.ServiceRegistrar, srv CalculateServiceServer) { + s.RegisterService(&CalculateService_ServiceDesc, srv) +} + +func _CalculateService_Sum_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(CalculateServiceServer).Sum(&calculateServiceSumServer{stream}) +} + +type CalculateService_SumServer interface { + SendAndClose(*SumResponse) error + Recv() (*SumRequest, error) + grpc.ServerStream +} + +type calculateServiceSumServer struct { + grpc.ServerStream +} + +func (x *calculateServiceSumServer) SendAndClose(m *SumResponse) error { + return x.ServerStream.SendMsg(m) +} + +func (x *calculateServiceSumServer) Recv() (*SumRequest, error) { + m := new(SumRequest) + if err := x.ServerStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +func _CalculateService_RandomNums_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(RandomNumsRequest) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(CalculateServiceServer).RandomNums(m, &calculateServiceRandomNumsServer{stream}) +} + +type CalculateService_RandomNumsServer interface { + Send(*RandomNumsResponse) error + grpc.ServerStream +} + +type calculateServiceRandomNumsServer struct { + grpc.ServerStream +} + +func (x *calculateServiceRandomNumsServer) Send(m *RandomNumsResponse) error { + return x.ServerStream.SendMsg(m) +} + +func _CalculateService_Average_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(CalculateServiceServer).Average(&calculateServiceAverageServer{stream}) +} + +type CalculateService_AverageServer interface { + Send(*AverageResponse) error + Recv() (*AverageRequest, error) + grpc.ServerStream +} + +type calculateServiceAverageServer struct { + grpc.ServerStream +} + +func (x *calculateServiceAverageServer) Send(m *AverageResponse) error { + return x.ServerStream.SendMsg(m) +} + +func (x *calculateServiceAverageServer) Recv() (*AverageRequest, error) { + m := new(AverageRequest) + if err := x.ServerStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +// CalculateService_ServiceDesc is the grpc.ServiceDesc for CalculateService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var CalculateService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "proto.CalculateService", + HandlerType: (*CalculateServiceServer)(nil), + Methods: []grpc.MethodDesc{}, + Streams: []grpc.StreamDesc{ + { + StreamName: "Sum", + Handler: _CalculateService_Sum_Handler, + ClientStreams: true, + }, + { + StreamName: "RandomNums", + Handler: _CalculateService_RandomNums_Handler, + ServerStreams: true, + }, + { + StreamName: "Average", + Handler: _CalculateService_Average_Handler, + ServerStreams: true, + ClientStreams: true, + }, + }, + Metadata: "calculator.proto", +} diff --git a/calculator/proto/calculator.proto b/calculator/proto/calculator.proto new file mode 100644 index 0000000..767cbfd --- /dev/null +++ b/calculator/proto/calculator.proto @@ -0,0 +1,40 @@ +syntax = "proto3"; + +package proto; + +option go_package = "git.gqnotes.com/guoqiang/grpcexercises/calculator/pb"; + +service CalculateService { + // 求和-客户端流式 + rpc Sum(stream SumRequest) returns(SumResponse) {} + // 生成一定数量的随机数-服务端流式 + rpc RandomNums(RandomNumsRequest) returns(stream RandomNumsResponse) {} + // 双向流式求平均值 + rpc Average(stream AverageRequest) returns(stream AverageResponse) {} +} + +message SumRequest { + int64 num =1; +} + + +message SumResponse { + int64 total = 1; +} + +message RandomNumsRequest { + int64 num =1; +} + +message RandomNumsResponse { + int64 num = 1; +} + +message AverageRequest { + int64 num =1; +} + +message AverageResponse { + float average = 1; +} + diff --git a/calculator/server/Average.go b/calculator/server/Average.go new file mode 100644 index 0000000..11f88fa --- /dev/null +++ b/calculator/server/Average.go @@ -0,0 +1,34 @@ +package main + +import ( + "git.gqnotes.com/guoqiang/grpcexercises/calculator/pb" + "io" +) + +// Average 计算平均数-双向流式 +func (s *Server) Average(stream pb.CalculateService_AverageServer) (err error) { + var sum int64 + var count int64 + + for { + req, err := stream.Recv() + + if err == io.EOF { + break + } + + if err != nil { + return err + } + + sum += req.Num + + count++ + + if err := stream.Send(&pb.AverageResponse{Average: float32(sum) / float32(count)}); err != nil { + return err + } + } + + return +} diff --git a/calculator/server/RandomNums.go b/calculator/server/RandomNums.go new file mode 100644 index 0000000..7e8c6f8 --- /dev/null +++ b/calculator/server/RandomNums.go @@ -0,0 +1,29 @@ +package main + +import ( + "git.gqnotes.com/guoqiang/grpcexercises/calculator/pb" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "math/rand" + "time" +) + +// RandomNums 生成一定数量的随机数-服务端流式 +func (s *Server) RandomNums(req *pb.RandomNumsRequest, stream pb.CalculateService_RandomNumsServer) error { + if req.Num <= 0 { + return status.Error(codes.InvalidArgument, "num must be greater than 0") + } + + for i := 0; i < int(req.Num); i++ { + // 生成一个随机整数 + s := rand.NewSource(time.Now().UnixNano()) + + if err := stream.Send(&pb.RandomNumsResponse{Num: s.Int63() % 1000}); err != nil { + return err + } + + // 间隔20ms + time.Sleep(20 * time.Millisecond) + } + return nil +} diff --git a/calculator/server/Sum.go b/calculator/server/Sum.go new file mode 100644 index 0000000..a69b78e --- /dev/null +++ b/calculator/server/Sum.go @@ -0,0 +1,33 @@ +package main + +import ( + "git.gqnotes.com/guoqiang/grpcexercises/calculator/pb" + "io" + "log" +) + +// Sum 计算和-客户端流式 +func (s *Server) Sum(stream pb.CalculateService_SumServer) error { + var sum int64 + + for { + req, err := stream.Recv() + + if err == io.EOF { + log.Printf("req.Num: %v", req) + break + } + + if err != nil { + return err + } + + sum += req.Num + } + + if err := stream.SendAndClose(&pb.SumResponse{Total: sum}); err != nil { + return err + } + + return nil +} diff --git a/calculator/server/main.go b/calculator/server/main.go new file mode 100644 index 0000000..7ab00d2 --- /dev/null +++ b/calculator/server/main.go @@ -0,0 +1,38 @@ +package main + +import ( + "git.gqnotes.com/guoqiang/grpcexercises/calculator/pb" + "google.golang.org/grpc" + "google.golang.org/grpc/reflection" + "log" + "net" +) + +func main() { + // 实现服务端逻辑,监听5633端口 + lis, err := net.Listen("tcp", ":5633") + + if err != nil { + log.Fatalf("failed to listen: %v", err) + return + } + + s := grpc.NewServer() + + // 反射服务 + reflection.Register(s) + + // 注册服务 + pb.RegisterCalculateServiceServer(s, &Server{}) + + log.Println("grpc server start") + + if err = s.Serve(lis); err != nil { + log.Fatalf("failed to serve: %v", err) + return + } +} + +type Server struct { + pb.UnimplementedCalculateServiceServer +} diff --git a/go.mod b/go.mod index ed34345..595d5f6 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module git.gqnotes.com/guoqiang/grpcexercises go 1.21.4 require ( + google.golang.org/appengine v1.6.7 google.golang.org/grpc v1.59.0 google.golang.org/protobuf v1.31.0 ) diff --git a/go.sum b/go.sum index 16f3bb4..9090f58 100644 --- a/go.sum +++ b/go.sum @@ -1,16 +1,25 @@ +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.14.0 h1:BONx9s002vGdD9umnlX1Po8vOZmrgH34qlHcD1MfK14= golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM= golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.12.0 h1:k+n5B8goJNdU7hSvEtMUz3d1Q6D/XW4COJSJR6fN0mc= golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= +google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/genproto/googleapis/rpc v0.0.0-20230822172742-b8732ec3820d h1:uvYuEyMHKNt+lT4K3bN6fGswmK8qSvcreM3BwjDh+y4= google.golang.org/genproto/googleapis/rpc v0.0.0-20230822172742-b8732ec3820d/go.mod h1:+Bk1OCOj40wS2hwAMA+aCW9ypzm63QTBBHp6lQ3p+9M= google.golang.org/grpc v1.59.0 h1:Z5Iec2pjwb+LEOqzpB2MR12/eKFhDPhuqW91O+4bwUk=