完整的项目结构
├─grpc01
│ │ go.mod
│ │ go.sum
│ │
│ ├─client
│ │ ├─client.go
│ │
│ ├─pbfile
│ │ │ hello.proto
│ │
│ └─server
│ ├─server.go
│ │
│ └─service
│ ├─hello.pb.go
│ ├─hello_grpc.pb.go
│
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.go
,hello_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",
}
服务端需要创建一个结构体,同时实现在hello.proto种声明的接口!
package main
import (
"context"
"google.golang.org/grpc"
"grpc01/service"
"log"
"net"
)
//1、声明一个server,里面是未实现的字段
type server struct {
service.UnimplementedProdServiceServer
}
//2、必须要实现在hello.proto里声明的远程调用接口,否则客户端会报:
//rpc error: code = Unimplemented desc = method GetProductStock not implemente
func (s *server) GetProductStock(ctx context.Context, in *service.ProductRequest) (*service.ProductResponse, error) {
return &service.ProductResponse{ProdStock: in.GetProdId()}, nil
}
func main() {
//1、创建服务
s := grpc.NewServer()
//2、注册服务
service.RegisterProdServiceServer(s, &server{})
//3、监听服务端口
listener, err := net.Listen("tcp", ":8002")
if err != nil {
log.Fatal("服务监听端口失败", err)
}
//4、启动服务
_ = s.Serve(listener)
}
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
service "grpc01/service"
"log"
)
func main() {
//1、 建立连接
conn, err := grpc.Dial(":8002", grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
// 2. 调用 hello_grpc.pb.go 中的NewProdServiceClient方法
productServiceClient := service.NewProdServiceClient(conn)
//3、调用rpc方法
resp, err := productServiceClient.GetProductStock(context.Background(), &service.ProductRequest{
ProdId: 233456,
})
if err != nil {
log.Fatal("调用gRPC方法错误: ", err)
}
fmt.Println("调用gRPC方法成功,ProdStock = ", resp.ProdStock)
}