网站首页 文章专栏 微服务讲解—(2)RPC框架
微服务讲解—(2)RPC框架
编辑时间:2022-05-07 15:10:28 作者:admin 浏览量:179

接上文,常用RPC框架有grpc、thrift、dubbo、motan,四者对比如下:

RPC对比
grpc
thrift
dubbo
motan
开发语言
跨语言
跨语言java
java
服务治理×
×
多种序列化
只支持protobuf
只支持thrift
多种注册中心
×
×
管理中心
×
×
跨语言通信
×
×
整体性能
353
4

# 使用grpc编写一个服务分如下三步:
1. 编写一个“.proto”文件,在该“.proto”文件中定义相关服务
2. 用protoc生成服务端和客户端共享的.pb.go文件
3. 实现一个简单的grpc客户端和grpc服务器

4. 环境准备
protoc下载地址:https://github.com/protocolbuffers/protobuf/releases
安装go插件:go get -u github.com/golang/protobuf/protoc-gen-go
grpc-go第三方库下载:go get -u google.golang.org/grpc

5. 在pb目录下,编辑 hello.proto 文件
syntax = "proto3";
package pb;
option go_package = ".;pb";//定义包名pb
service Greeter { //定义 rpc 服务
 rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
 string name = 1;
}
message HelloReply {
 string message = 1;
}

6. 在pb目录执行以下命令,生成 hello.proto.go
protoc --go_out=plugins=grpc:. hello.proto
该文件主要包括,服务端(helloServer)相关数据结构及服务函数;客户端(helloClient)相关数据结构及服务函数;客户端和服务端进行数据交互相关的消息初始化、传递、接收的数据结构及函数

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

package pb

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 HelloRequest struct {
  state         protoimpl.MessageState
  sizeCache     protoimpl.SizeCache
  unknownFields protoimpl.UnknownFields

  Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
}

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

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

func (*HelloRequest) ProtoMessage() {}

func (x *HelloRequest) 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 HelloRequest.ProtoReflect.Descriptor instead.
func (*HelloRequest) Descriptor() ([]byte, []int) {
  return file_hello_proto_rawDescGZIP(), []int{0}
}

func (x *HelloRequest) GetName() string {
  if x != nil {
     return x.Name
  }
  return ""
}

type HelloReply struct {
  state         protoimpl.MessageState
  sizeCache     protoimpl.SizeCache
  unknownFields protoimpl.UnknownFields

  Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"`
}

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

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

func (*HelloReply) ProtoMessage() {}

func (x *HelloReply) 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 HelloReply.ProtoReflect.Descriptor instead.
func (*HelloReply) Descriptor() ([]byte, []int) {
  return file_hello_proto_rawDescGZIP(), []int{1}
}

func (x *HelloReply) GetMessage() string {
  if x != nil {
     return x.Message
  }
  return ""
}

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, 0x02, 0x70,
  0x62, 0x22, 0x22, 0x0a, 0x0c, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
  0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52,
  0x04, 0x6e, 0x61, 0x6d, 0x65, 0x22, 0x26, 0x0a, 0x0a, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65,
  0x70, 0x6c, 0x79, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x01,
  0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x32, 0x39, 0x0a,
  0x07, 0x47, 0x72, 0x65, 0x65, 0x74, 0x65, 0x72, 0x12, 0x2e, 0x0a, 0x08, 0x53, 0x61, 0x79, 0x48,
  0x65, 0x6c, 0x6c, 0x6f, 0x12, 0x10, 0x2e, 0x70, 0x62, 0x2e, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52,
  0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x0e, 0x2e, 0x70, 0x62, 0x2e, 0x48, 0x65, 0x6c, 0x6c,
  0x6f, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x22, 0x00, 0x42, 0x06, 0x5a, 0x04, 0x2e, 0x3b, 0x70, 0x62,
  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{}{
  (*HelloRequest)(nil), // 0: pb.HelloRequest
  (*HelloReply)(nil),   // 1: pb.HelloReply
}
var file_hello_proto_depIdxs = []int32{
  0, // 0: pb.Greeter.SayHello:input_type -> pb.HelloRequest
  1, // 1: pb.Greeter.SayHello:output_type -> pb.HelloReply
  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.(*HelloRequest); 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.(*HelloReply); 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
}

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

// GreeterClient is the client API for Greeter service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type GreeterClient interface {
  SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error)
}

type greeterClient struct {
  cc grpc.ClientConnInterface
}

func NewGreeterClient(cc grpc.ClientConnInterface) GreeterClient {
  return &greeterClient{cc}
}

func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) {
  out := new(HelloReply)
  err := c.cc.Invoke(ctx, "/pb.Greeter/SayHello", in, out, opts...)
  if err != nil {
     return nil, err
  }
  return out, nil
}

// GreeterServer is the server API for Greeter service.
type GreeterServer interface {
  SayHello(context.Context, *HelloRequest) (*HelloReply, error)
}

// UnimplementedGreeterServer can be embedded to have forward compatible implementations.
type UnimplementedGreeterServer struct {
}

func (*UnimplementedGreeterServer) SayHello(context.Context, *HelloRequest) (*HelloReply, error) {
  return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented")
}

func RegisterGreeterServer(s *grpc.Server, srv GreeterServer) {
  s.RegisterService(&_Greeter_serviceDesc, srv)
}

func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
  in := new(HelloRequest)
  if err := dec(in); err != nil {
     return nil, err
  }
  if interceptor == nil {
     return srv.(GreeterServer).SayHello(ctx, in)
  }
  info := &grpc.UnaryServerInfo{
     Server:     srv,
     FullMethod: "/pb.Greeter/SayHello",
  }
  handler := func(ctx context.Context, req interface{}) (interface{}, error) {
     return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest))
  }
  return interceptor(ctx, in, info, handler)
}

var _Greeter_serviceDesc = grpc.ServiceDesc{
  ServiceName: "pb.Greeter",
  HandlerType: (*GreeterServer)(nil),
  Methods: []grpc.MethodDesc{
     {
        MethodName: "SayHello",
        Handler:    _Greeter_SayHello_Handler,
     },
  },
  Streams:  []grpc.StreamDesc{},
  Metadata: "hello.proto",
}

7. 编写 client.go 及 server.go

------------------------------------------------------------client.go
package main

import (
   "context"
   "fmt"
   "google.golang.org/grpc"
   "test/grpc_test/pb"
)

func main() {
   // 连接服务器
   conn, err := grpc.Dial(":8090", grpc.WithInsecure())
   if err != nil {
      fmt.Printf("连接服务端失败: %s", err)
      return
   }
   defer conn.Close()

   // 新建一个客户端
   c := pb.NewGreeterClient(conn) //调用pb包
   // 调用服务端函数
   r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: "horika"}) //调用SayHello函数
   if err != nil {
      fmt.Printf("调用服务端代码失败: %s", err)
      return
   }
   fmt.Printf("调用成功: %s", r.Message)
}
------------------------------------------------------------server.go
package main

import (
"context"
"fmt"
"test/grpc_test/pb"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
"net"
)

// 定义server
type server struct {}

func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
   return &pb.HelloReply{Message: "hello " + in.Name}, nil
}

func main() {
   // 监听本地端口
   lis, err := net.Listen("tcp", ":8090")
   if err != nil {
      fmt.Printf("监听端口失败: %s", err)
      return
   }
   // 创建gRPC服务器
   s := grpc.NewServer()
   // 注册服务
   pb.RegisterGreeterServer(s, &server{})
   reflection.Register(s)
   err = s.Serve(lis)
   if err != nil {
      fmt.Printf("开启服务失败: %s", err)
      return
   }
}
启动server后,运行client,调用成功。

启动server后,运

image.png

来说两句吧
最新评论