grpc客户端和服务端利用protoc进行通信
./message/message.proto
syntax = "proto3"; option go_package="./;message"; package message; //订单请求参数 message OrderRequest { string orderId = 1; //1,2编号 int64 timeStamp = 2; } //订单信息 message OrderInfo { string OrderId = 1; string OrderName = 2; string OrderStatus = 3; } //订单服务service定义 service OrderService{ rpc GetOrderInfo(OrderRequest) returns (OrderInfo); } //运行:protoc --go_out=plugins=grpc:. message.proto //生成:message.pb.go
./message.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 // protoc v3.19.0 // source: message.proto package message import ( context "context" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" 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 OrderRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OrderId string `protobuf:"bytes,1,opt,name=orderId,proto3" json:"orderId,omitempty"` //1,2编号 TimeStamp int64 `protobuf:"varint,2,opt,name=timeStamp,proto3" json:"timeStamp,omitempty"` } func (x *OrderRequest) Reset() { *x = OrderRequest{} if protoimpl.UnsafeEnabled { mi := &file_message_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *OrderRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*OrderRequest) ProtoMessage() {} func (x *OrderRequest) ProtoReflect() protoreflect.Message { mi := &file_message_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 OrderRequest.ProtoReflect.Descriptor instead. func (*OrderRequest) Descriptor() ([]byte, []int) { return file_message_proto_rawDescGZIP(), []int{0} } func (x *OrderRequest) GetOrderId() string { if x != nil { return x.OrderId } return "" } func (x *OrderRequest) GetTimeStamp() int64 { if x != nil { return x.TimeStamp } return 0 } //订单信息 type OrderInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OrderId string `protobuf:"bytes,1,opt,name=OrderId,proto3" json:"OrderId,omitempty"` OrderName string `protobuf:"bytes,2,opt,name=OrderName,proto3" json:"OrderName,omitempty"` OrderStatus string `protobuf:"bytes,3,opt,name=OrderStatus,proto3" json:"OrderStatus,omitempty"` } func (x *OrderInfo) Reset() { *x = OrderInfo{} if protoimpl.UnsafeEnabled { mi := &file_message_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *OrderInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*OrderInfo) ProtoMessage() {} func (x *OrderInfo) ProtoReflect() protoreflect.Message { mi := &file_message_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 OrderInfo.ProtoReflect.Descriptor instead. func (*OrderInfo) Descriptor() ([]byte, []int) { return file_message_proto_rawDescGZIP(), []int{1} } func (x *OrderInfo) GetOrderId() string { if x != nil { return x.OrderId } return "" } func (x *OrderInfo) GetOrderName() string { if x != nil { return x.OrderName } return "" } func (x *OrderInfo) GetOrderStatus() string { if x != nil { return x.OrderStatus } return "" } var File_message_proto protoreflect.FileDescriptor var file_message_proto_rawDesc = []byte{ 0x0a, 0x0d, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x46, 0x0a, 0x0c, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x49, 0x64, 0x12, 0x1c, 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x53, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x53, 0x74, 0x61, 0x6d, 0x70, 0x22, 0x65, 0x0a, 0x09, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x18, 0x0a, 0x07, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x49, 0x64, 0x12, 0x1c, 0x0a, 0x09, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x32, 0x49, 0x0a, 0x0c, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x39, 0x0a, 0x0c, 0x47, 0x65, 0x74, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x15, 0x2e, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x2e, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x12, 0x2e, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x2e, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x42, 0x0c, 0x5a, 0x0a, 0x2e, 0x2f, 0x3b, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_message_proto_rawDescOnce sync.Once file_message_proto_rawDescData = file_message_proto_rawDesc ) func file_message_proto_rawDescGZIP() []byte { file_message_proto_rawDescOnce.Do(func() { file_message_proto_rawDescData = protoimpl.X.CompressGZIP(file_message_proto_rawDescData) }) return file_message_proto_rawDescData } var file_message_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_message_proto_goTypes = []interface{}{ (*OrderRequest)(nil), // 0: message.OrderRequest (*OrderInfo)(nil), // 1: message.OrderInfo } var file_message_proto_depIdxs = []int32{ 0, // 0: message.OrderService.GetOrderInfo:input_type -> message.OrderRequest 1, // 1: message.OrderService.GetOrderInfo:output_type -> message.OrderInfo 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_message_proto_init() } func file_message_proto_init() { if File_message_proto != nil { return } if !protoimpl.UnsafeEnabled { file_message_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*OrderRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_message_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*OrderInfo); 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_message_proto_rawDesc, NumEnums: 0, NumMessages: 2, NumExtensions: 0, NumServices: 1, }, GoTypes: file_message_proto_goTypes, DependencyIndexes: file_message_proto_depIdxs, MessageInfos: file_message_proto_msgTypes, }.Build() File_message_proto = out.File file_message_proto_rawDesc = nil file_message_proto_goTypes = nil file_message_proto_depIdxs = nil } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConnInterface // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion6 // OrderServiceClient is the client API for OrderService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type OrderServiceClient interface { GetOrderInfo(ctx context.Context, in *OrderRequest, opts ...grpc.CallOption) (*OrderInfo, error) } type orderServiceClient struct { cc grpc.ClientConnInterface } func NewOrderServiceClient(cc grpc.ClientConnInterface) OrderServiceClient { return &orderServiceClient{cc} } func (c *orderServiceClient) GetOrderInfo(ctx context.Context, in *OrderRequest, opts ...grpc.CallOption) (*OrderInfo, error) { out := new(OrderInfo) err := c.cc.Invoke(ctx, "/message.OrderService/GetOrderInfo", in, out, opts...) if err != nil { return nil, err } return out, nil } // OrderServiceServer is the server API for OrderService service. type OrderServiceServer interface { GetOrderInfo(context.Context, *OrderRequest) (*OrderInfo, error) } // UnimplementedOrderServiceServer can be embedded to have forward compatible implementations. type UnimplementedOrderServiceServer struct { } func (*UnimplementedOrderServiceServer) GetOrderInfo(context.Context, *OrderRequest) (*OrderInfo, error) { return nil, status.Errorf(codes.Unimplemented, "method GetOrderInfo not implemented") } func RegisterOrderServiceServer(s *grpc.Server, srv OrderServiceServer) { s.RegisterService(&_OrderService_serviceDesc, srv) } func _OrderService_GetOrderInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(OrderRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(OrderServiceServer).GetOrderInfo(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/message.OrderService/GetOrderInfo", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(OrderServiceServer).GetOrderInfo(ctx, req.(*OrderRequest)) } return interceptor(ctx, in, info, handler) } var _OrderService_serviceDesc = grpc.ServiceDesc{ ServiceName: "message.OrderService", HandlerType: (*OrderServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "GetOrderInfo", Handler: _OrderService_GetOrderInfo_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "message.proto", }
./Client.go
package main import ( "WLBC/GRPC2/message" "context" "fmt" "google.golang.org/grpc" "time" ) func main(){ conn, err := grpc.Dial("localhost:8090", grpc.WithInsecure()) if err != nil { panic(err.Error()) } defer conn.Close() orderServiceClient := message.NewOrderServiceClient(conn) orderRequest := &message.OrderRequest{OrderId: "201907300001", TimeStamp: time.Now().Unix()} orderInfo, err := orderServiceClient.GetOrderInfo(context.Background(), orderRequest) if orderInfo != nil { fmt.Println(orderInfo.GetOrderId()) fmt.Println(orderInfo.GetOrderName()) fmt.Println(orderInfo.GetOrderStatus()) } }
./Server.go
package main import ( "WLBC/GRPC2/message" "context" "errors" "fmt" "google.golang.org/grpc" "net" "time" ) type OrderServiceImpl struct { } //具体的方法实现 func (os *OrderServiceImpl) GetOrderInfo(ctx context.Context, request *message.OrderRequest) (*message.OrderInfo, error) { orderMap := map[string]message.OrderInfo{ "201907300001": message.OrderInfo{OrderId: "201907300001", OrderName: "衣服", OrderStatus: "已付款"}, "201907310001": message.OrderInfo{OrderId: "201907310001", OrderName: "零食", OrderStatus: "已付款"}, "201907310002": message.OrderInfo{OrderId: "201907310002", OrderName: "食品", OrderStatus: "未付款"}, } var response *message.OrderInfo current := time.Now().Unix() if request.TimeStamp > current { *response = message.OrderInfo{OrderId: "0", OrderName: "", OrderStatus: "订单信息异常"} } else { result := orderMap[request.OrderId] if result.OrderId != "" { fmt.Println(result) return &result, nil } else { return nil, errors.New("server error") } } return response, nil } func main() { server := grpc.NewServer() message.RegisterOrderServiceServer(server, new(OrderServiceImpl)) lis, err := net.Listen("tcp", ":8090") if err != nil { panic(err.Error()) } server.Serve(lis) }
Mamba never out

浙公网安备 33010602011771号