RPC在go语言中的使用(二)Protocol Buffer是什么?
这里我们简单聊下什么是Protocol Buffer?
Protocol Buffer 是一种数据序列化的工具,说到序列化工具就不得不提xml、json。他们之间有什么区别?
首先Protocol Buffer序列化之后的数据是二进制流,是不可读的。无法通过直接打印的方式读取到里面的内容。
第二就是需要事先定义好数据的格式(.proto文件),在反序列化时需要使用到这个文件。
无论是xml还是json,内容都是可读的,反序列化也不需要预定义好格式,可直接进行进行反序列。
为什么存在Protocol Buffer呢?是因为在传输数据时数据量更小,速度更快,相比较xml、json而言。
Protocol Buffer是跨平台、跨语言、可扩展的序列化工具,编写一个proto文件,使用编译器生成特定语言的源代码。
Protocol Buffer定义的数据格式通常都是一个以.proto结尾的文件,文件内的message代表的是一个数据结构,message里面定义了该结构的每一个属性。service
使用Protocol Buffer编写一个golang的rpc接口示例
Arith.proto
syntax="proto3";
package pb;
option go_package ="../pb";
定义参数
message Args {
int32 a = 1;
int32 b = 2;
}
定义返回结构
message Answer {
int32 sum = 1;
}
定义rpc方法
service Arith {
rpc calc(Args) returns (Answer);
}
生成服务端文件
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v3.19.4
// source: calc.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 Args struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
A int32 `protobuf:"varint,1,opt,name=a,proto3" json:"a,omitempty"`
B int32 `protobuf:"varint,2,opt,name=b,proto3" json:"b,omitempty"`
}
func (x *Args) Reset() {
*x = Args{}
if protoimpl.UnsafeEnabled {
mi := &file_calc_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Args) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Args) ProtoMessage() {}
func (x *Args) ProtoReflect() protoreflect.Message {
mi := &file_calc_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 Args.ProtoReflect.Descriptor instead.
func (*Args) Descriptor() ([]byte, []int) {
return file_calc_proto_rawDescGZIP(), []int{0}
}
func (x *Args) GetA() int32 {
if x != nil {
return x.A
}
return 0
}
func (x *Args) GetB() int32 {
if x != nil {
return x.B
}
return 0
}
// 定义返回结构
type Answer struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Sum int32 `protobuf:"varint,1,opt,name=sum,proto3" json:"sum,omitempty"`
}
func (x *Answer) Reset() {
*x = Answer{}
if protoimpl.UnsafeEnabled {
mi := &file_calc_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Answer) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Answer) ProtoMessage() {}
func (x *Answer) ProtoReflect() protoreflect.Message {
mi := &file_calc_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 Answer.ProtoReflect.Descriptor instead.
func (*Answer) Descriptor() ([]byte, []int) {
return file_calc_proto_rawDescGZIP(), []int{1}
}
func (x *Answer) GetSum() int32 {
if x != nil {
return x.Sum
}
return 0
}
var File_calc_proto protoreflect.FileDescriptor
var file_calc_proto_rawDesc = []byte{
0x0a, 0x0a, 0x63, 0x61, 0x6c, 0x63, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x02, 0x70, 0x62,
0x22, 0x22, 0x0a, 0x04, 0x41, 0x72, 0x67, 0x73, 0x12, 0x0c, 0x0a, 0x01, 0x61, 0x18, 0x01, 0x20,
0x01, 0x28, 0x05, 0x52, 0x01, 0x61, 0x12, 0x0c, 0x0a, 0x01, 0x62, 0x18, 0x02, 0x20, 0x01, 0x28,
0x05, 0x52, 0x01, 0x62, 0x22, 0x1a, 0x0a, 0x06, 0x41, 0x6e, 0x73, 0x77, 0x65, 0x72, 0x12, 0x10,
0x0a, 0x03, 0x73, 0x75, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x73, 0x75, 0x6d,
0x32, 0x25, 0x0a, 0x05, 0x41, 0x72, 0x69, 0x74, 0x68, 0x12, 0x1c, 0x0a, 0x04, 0x63, 0x61, 0x6c,
0x63, 0x12, 0x08, 0x2e, 0x70, 0x62, 0x2e, 0x41, 0x72, 0x67, 0x73, 0x1a, 0x0a, 0x2e, 0x70, 0x62,
0x2e, 0x41, 0x6e, 0x73, 0x77, 0x65, 0x72, 0x42, 0x07, 0x5a, 0x05, 0x2e, 0x2e, 0x2f, 0x70, 0x62,
0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_calc_proto_rawDescOnce sync.Once
file_calc_proto_rawDescData = file_calc_proto_rawDesc
)
func file_calc_proto_rawDescGZIP() []byte {
file_calc_proto_rawDescOnce.Do(func() {
file_calc_proto_rawDescData = protoimpl.X.CompressGZIP(file_calc_proto_rawDescData)
})
return file_calc_proto_rawDescData
}
var file_calc_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_calc_proto_goTypes = []interface{}{
(*Args)(nil), // 0: pb.Args
(*Answer)(nil), // 1: pb.Answer
}
var file_calc_proto_depIdxs = []int32{
0, // 0: pb.Arith.calc:input_type -> pb.Args
1, // 1: pb.Arith.calc:output_type -> pb.Answer
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_calc_proto_init() }
func file_calc_proto_init() {
if File_calc_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_calc_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Args); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_calc_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Answer); 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_calc_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_calc_proto_goTypes,
DependencyIndexes: file_calc_proto_depIdxs,
MessageInfos: file_calc_proto_msgTypes,
}.Build()
File_calc_proto = out.File
file_calc_proto_rawDesc = nil
file_calc_proto_goTypes = nil
file_calc_proto_depIdxs = nil
}
server.go文件内容
package main
import (
"context"
"github.com/mosesyu95/proto/pb"
"google.golang.org/grpc"
"log"
"net"
)
// Arith 定义算数算法服务
type Arith struct {
}
func (a *Arith) Calc(ctx context.Context,args *pb.Args) (*pb.Answer, error) {
log.Printf("receive %+v \n", args)
var res = &pb.Answer{Sum: args.A + args.B}
return res ,nil
}
func main() {
lis, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatalln(err)
}
grpcserver := grpc.NewServer()
pb.RegisterArithServer(grpcserver, &Arith{})
go grpcserver.Serve(lis)
select {
}
}
client.go
package main
import (
"context"
"fmt"
"github.com/mosesyu95/proto/pb"
"google.golang.org/grpc"
"log"
)
func main() {
conn, err := grpc.Dial("127.0.0.1:8080",grpc.WithInsecure())
if err != nil {
log.Fatalln("dailing error: ", err)
}
defer conn.Close()
arithClient := pb.NewArithClient(conn)
req := &pb.Args{
A: 2,
B: 4,
}
res, err := arithClient.Calc(context.Background(),req )
fmt.Printf("%d + %d = %d \n", req.A, req.B, res.Sum)
}
执行结果
代码位置:https://github.com/mosesyu95/proto.git