• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

[golang 微服务] 3. ProtoBuf认识,安装以和golang ProtoBuf使用

武飞扬头像
zhoupenghui168
帮助1

一.protobuf简介

  1. 前言

在移动互联网时代, 手机流量电量是最为有限的资源,而移动端的即时通讯应用无疑必须得直面这两点。解决流量过大的基本方法就是 使用高度压缩的通信协议,而数据压缩后流量减小带来的自然结果也就是省电:因为大数据量的传输必然需要 更久的网络操作数据序列化反序列化操作,这些都是电量消耗过快的根源。当前即时通讯应用中最热门的 通信协议无疑就是 Google的Protobuf了,基于它的优秀表现, 微信和手机QQ这样的主流IM应用也早已在使用它
  1. 简介

ProtobufProtocol Buffers的简称,它是Google公司开发的一种 数据描述语言,是一种 轻便高效结构化数据存储格式,可以 用于结构化数据,或者说 序列化,它很适合做 数据存储RPC 数据交换格式,可用于 通讯协议数据存储等领域的语言无关、平台无关、可扩展的 序列化结构数据格式,是一种 灵活高效自动化的机制,用于 序列化结构化数据,对比于 XML和JSON,它 更小、更快更简单,总之它是 微服务中需要使用的东西. 目前提供了 C 、Java、Python 三种语言的 API(即时通讯网注:Protobuf官方工程主页上显示的已支持的开发语言多达10种,分别有:C 、Java、Python、Objective-C、C#、JavaNano、JavaScript、Ruby、Go、PHP,基本上主流的语言都已支持).
Protobuf刚开源时的定位类似于XML、JSON等数据描述语言,通过 附带工具生成代码实现将结构化数据序列化的功能.这里更关注的是Protobuf作为 接口规范的描述语言,可以 作为设计安全的跨语言RPC接口的基础工具
学新通
  1. 需要了解几点

  • protobuf是类似与json一样的数据描述语言(数据格式

  • protobuf非常适合于RPC数据交换格式

  • 序列化:将数据结构或对象转换成二进制串的过程

  • 反序列化:将在序列化过程中所产生的二进制串转换成数据结构对象的过程

  1. protobuf的优势和劣势

(1).优势

  • 序列化后体积相比Json和XML很小,适合网络传输

  • 支持跨平台多语言

  • 消息格式升级和兼容性很好,不必破坏旧的数据格式,就能对数据结构进行更新

  • 序列化反序列化速度很快,快于Json的处理速度

  • 跨平台、跨语言、可扩展性强

  • 维护成本低,多平台只需要维护一套对象协议文件,即.proto文件

  • 加密性好,http传输内容抓包只能抓到字节数据

(2).劣势

  • 应用不够广(相比xml和json)

  • 二进制格式导致可读性差

  • 乏自描述

二.protobuf的安装

  1. windows电脑上面安装protocol buffers

github地址: https://github.com/protocolbuffers/protobuf
版本下载地址: https://github.com/protocolbuffers/protobuf/tags

(1).下载

这里下载protobuf v3.15.5 的版本,下载地址: https://github.com/protocolbuffers/protobuf/releases/tag/v3.15.5,选择 protoc-3.15.5-win64.zip 下载,减压并将解压得到的文件中的bin目录路径添加到系统变量中
1).官网下载
学新通
2).解压
学新通
3).添加到环境变量
环境变量添加操作见文档: 安装ElasticSearch之前的准备工作jdk的安装
系统变量找到Path ,把 bin目录路径添加 ,然后完成就可以了
学新通
学新通
4).重启计算机
配置了环境变量,为了使其生效,需要重启计算机

(2).查看版本

出现以下显示,说明protobuf 安装成功
学新通

(3).protobuf的go语言插件protoc-gen-go插件

go install github.com/golang/protobuf/protoc-gen-go@latest

安装结果如下:

  1.  
    F:\www\go-data\src\go_code\micro>go install github.com/golang/protobuf/protoc-gen-go@latest
  2.  
    go: downloading github.com/golang/protobuf v1.5.3
  3.  
    go: downloading 谷歌.golang.org/protobuf v1.26.0
  4.  
     
  5.  
    F:\www\go-data\src\go_code\micro>
  1. Mac电脑上面安装protocol buffers

Linux和Mac安装方式类似

(1).方式一:安装protobuf (推荐)

如果电脑上面没有brew先安装brew
brew install protobuf

(2).方式二:安装protobuf

如果电脑没有安装brew也可以使用下面方法安装
(1).下载
下载地址: https://github.com/protocolbuffers/protobuf/releases
选择适合macos的protobuf,比如选择protoc-3.12.1-osx-x86_64.zip
(2).解压
解压包得到protoc-3.12.1-osx-x86_64
(3).重命名
mv protoc-3.12.1-osx-x86_64 protobuf
(4).配置环境变量
  1.  
    vim ~/.bash_profile
  2.  
     
  3.  
    export PROTOBUF=/Users/nacos/Library/protobuf
  4.  
    export PATH=$PATH:$PROTOBUF/bin
(5).刷新配置
source ~/.bash_profile
(6).查看版本
protoc --version

(3).protobuf的go语言插件protoc-gen-go插件

go install github.com/golang/protobuf/protoc-gen-go@latest

(4).配置环境变量

安装完毕后如果提示 没法使用protoc-gen-go,还需要把 gopath对应的bin目录配置到环境变量
  1.  
    vim ~/.bash_profile
  2.  
     
  3.  
    export PATH=/Users/nacos/go/bin:$PATH

(5).刷新配置

配置完保存记得刷新下配置
source ~/.bash_profile
  1. 测试protoc和protoc-gen-go是否全部配置成功

(1).新建 test.proto

  1.  
    syntax = "proto3";
  2.  
    option go_package = "./protoService";
  3.  
    message Userinfo {
  4.  
    string name = 1;
  5.  
    int32 age = 2;
  6.  
    repeated string hobby = 3;
  7.  
    }

(2).把proto 文件编译成go文件

F:\www\go-data\src\go_code\micro\protoc>protoc --go_out=./ *.proto

(3).结果

运行以上命令后,正确的结果如下:
学新通

三.protobuf 的用法

参考文档(需科学上网): https://developers.谷歌.com/protocol-buffers/docs/proto3
  1. protobuf 简单语法

(1).案例引入

先看代码,然后根据代码讲解,创建一个后缀为.proto的protobuf语法的文件,如下:
  1.  
    syntax = "proto3"; //指定版本信息,不指定会报错,默认是proto2
  2.  
     
  3.  
    //分号(;)前面的表示当前.proto文件所在的路径,分号后面表示生成go文件的包名
  4.  
    option go_package = "./proto;helloworld";
  5.  
     
  6.  
    //message定义一种消息类型,关键字message定义结构,并且结构中可以嵌套定义结构,message定义的内容和生成一个结构体
  7.  
    message Person{
  8.  
        //名字
  9.  
        string name = 1;
  10.  
        //年龄
  11.  
        int32 age = 2 ;
  12.  
        //爱好
  13.  
        repeated string hobby = 3; // repeadted关键字类似与go中的切片,编译之后对应的也是go的切片,golang中会生成string类型的切片
  14.  
    }

(2).总结

  • protobuf消息的定义(或者称为描述)通常都写在一个以 .proto 结尾的文件中

  • 该文件的第一行指定正在使用 proto3 语法:如果不这样做,协议缓冲区编译器将假定正在使用proto2,这也必须是文件的第一个非空的非注释行

  • 第二行 option go_package 指定生成go文件的目录以及包名称

  • 最后message关键字定义一个Person消息体类似于go语言中的结构体,是包含一系列类型数据的集合,许多标准的简单数据类型都可以作为字段类型,包括 bool , int32 ,float , double ,和 string 。也可以使用其他message类型作为字段类型

  • 在message中有一个字符串类型的value成员,该成员编码时用1代替名字,在json中是通过成员的名字来绑定对应的数据,但是Protobuf编码却是通过成员的唯一编号来绑定对应的数据,因此Protobuf编码后数据的体积会比较小,能够快速传输,缺点是不利于阅读

(3).message的格式说明

消息由 至少一个字段组合而成,类似于Go语言中的 结构体,每个字段都有一定的格式:
  1.  
    //注释格式 注释尽量也写在内容上方
  2.  
    (字段修饰符)数据类型 字段名称 = 唯一的编号标签值;
  • 唯一的编号标签:代表每个字段的一个唯一的编号标签,在同一个消息里不可以重复,这些编号标签用与在消息二进制格式中标识字段,并且消息一旦定义就不能更改,需要说明的是标签在1到15范围的采用一个字节进行编码16 ~ 2047采用双字节编码,所以通常将标签1到15用于频繁发生的消息字段,编号标签大小的范围是1到2的29次,19000-19999是官方预留的值,不能使用

  • 注释格式:向.proto文件添加注释,可以使用C/C /java/Go风格的双斜杠(//) 语法格式或者 /*.....*/

  • 可以在单个.proto中定义多种消息类型,如果要定义多个相关消息,这很有用——例如,如果想定义与搜索响应消息类型相对应的回复消息格式,可以将其添加到该.proto中

  1.  
    message SearchRequest {
  2.  
    string query = 1;
  3.  
    int32 page_number = 2;
  4.  
    int32 result_per_page = 3;
  5.  
    }
  6.  
     
  7.  
    message SearchResponse {
  8.  
    ...
  9.  
    }

message常见的数据类型与go中类型对比

学新通
学新通

(4).proto2和proto3差别

proto3 比 proto2 支持更多语言但 更简洁,去掉了一些复杂的语法和特性,更 强调约定弱化语法
区别
  • 第一行非空白非注释行,必须写:syntax = “proto3”

  • 字段规则移除了 “required”,并把 “optional” 改名为 “singular”

  • proto3 repeated标量数值类型默认packed,而proto2默认不开启

在 proto2 中,需要明确使用 [packed=true] 来为字段指定比较紧凑的 packed 编码方式
  • 语言增加 Go、Ruby、JavaNano 支持

  • proto2可以选填default,而proto3只能使用系统默认的

在 proto2 中,可以使用 default 选项为某一字段指定默认值, 在 proto3 中,字段的默认值只能根据字段类型由系统决定,也就是说, 默认值全部是约定好的,而不再提供指定默认值的语法
  • proto3必须有一个零值,以便可以使用 0 作为数字默认值,零值需要是第一个元素,以便与proto2语义兼容,其中第一个枚举值始终是默认值,proto2则没有这项要求

  • proto3在3.5版本之前会丢弃未知字段,但在 3.5 版本中,重新引入了未知字段的保留以匹配 proto2 行为,在 3.5 及更高版本中,未知字段在解析过程中保留并包含在序列化输出中

  • proto3移除了proto2的扩展,新增了Any(仍在开发中)和JSON映射

proto3字段规则
  • singular: 可以有零个或其中一个字段(但不超过一个)

  • repeated: 该字段可以重复任意次数(包括零次),重复值的顺序将被保留

  • 在proto 3中,可扩展的repeated字段为数字类型的默认编码

在proto2中,规则为:
required:必须有一个
optional:0或者1个
repeated:任意数量(包括0)
  1. protobuf高级用法

(1).message嵌套

messsage除了能放 简单数据类型外,还能存放 另外的message类型,如下:
  1.  
    syntax = "proto3";//指定版本信息,不指定会报错
  2.  
    option go_package = "./proto;helloworld";
  3.  
     
  4.  
    //message为关键字,作用为定义一种消息类型
  5.  
    message Person{
  6.  
        //名字
  7.  
        string name = 1;
  8.  
        //年龄
  9.  
        int32 age = 2 ;
  10.  
        //定义一个message
  11.  
        message PhoneNumber {
  12.  
            string number = 1;
  13.  
            int64 type = 2;
  14.  
        }
  15.  
        PhoneNumber phone = 3;
  16.  
    }
学新通

(2).repeated关键字

repeadted关键字类似与 go中的切片,编译之后对应的也是go的切片,用法如下
  1.  
    syntax = "proto3";//指定版本信息,不指定会报错
  2.  
    option go_package = "./proto;helloworld";
  3.  
     
  4.  
    //message为关键字,作用为定义一种消息类型
  5.  
    message Person{
  6.  
        //名字  
  7.  
        string name = 1;
  8.  
        //年龄   
  9.  
        int32 age = 2 ;
  10.  
        //定义一个message
  11.  
        message PhoneNumber {
  12.  
            string number = 1;
  13.  
            int64 type = 2;
  14.  
        }
  15.  
        // repeated: 该字段可以重复任意次数(包括零次)。重复值的顺序将被保留
  16.  
        repeated PhoneNumber phone = 3;
  17.  
    }
学新通

(3).默认值

当解析 message 时,如果被编码的 message 里没有包含某些变量,那么根据类型不同,他们会有不同的默认值,具体如下:
  • string:默认是空的字符串

  • byte:默认是空的bytes

  • bool:默认为false

  • numeric:默认为0

  • enums:默认值是第一个定义的枚举值,该值必须为0

  • repeated字段默认值是空列表

  • message字段的默认值为空对象

收到数据后反序列化后,对于 标准值类型的数据,比如bool,如果它的值是 false,那么就无法判断这个值是对方设置的,还是对方压根就没给这个变量设置值

(4).enum关键字

在定义消息类型时,可能会希望其中一个字段有一个 预定义的值列表,比如说,电话号码字段有个类型,这个类型可以是:home,work,mobile,可以通过enum在消息定义中添加每个可能值的常量来非常简单的执行此操作,实例如下
  1.  
    syntax = "proto3";//指定版本信息,不指定会报错
  2.  
     
  3.  
    package pb;//后期生成go文件的包名
  4.  
     
  5.  
    //message为关键字,作用为定义一种消息类型
  6.  
    message Person{   
  7.  
        //名字
  8.  
        string name = 1;
  9.  
        //年龄
  10.  
        int32 age = 2 ;
  11.  
     
  12.  
        //定义一个message
  13.  
        message PhoneNumber {
  14.  
           string number = 1;
  15.  
            PhoneType type = 2;
  16.  
        }
  17.  
     
  18.  
        repeated PhoneNumber phone = 3;
  19.  
     
  20.  
    // 枚举:可以在message内定义
  21.  
        enum Corpus {
  22.  
    UNIVERSAL = 0;
  23.  
    WEB = 1;
  24.  
    IMAGES = 2;
  25.  
    LOCAL = 3;
  26.  
    NEWS = 4;
  27.  
    PRODUCTS = 5;
  28.  
    VIDEO = 6;
  29.  
    }
  30.  
    Corpus corpus = 4;
  31.  
    }
  32.  
     
  33.  
    //enum为关键字,作用为定义一种枚举类型,可以在message外定义
  34.  
    enum PhoneType {
  35.  
        MOBILE = 0;
  36.  
        HOME = 1;
  37.  
        WORK = 2;
  38.  
    }
学新通
如上,enum的 第一个常量映射为0,每个枚举定义 必须包含一个映射到零的常量作为其 第一个元素,这是因为:
必须有一个零值,以便可以使用0作为数字 默认值
零值必须是第一个元素,以便与proto2语义 兼容,其中第一个枚举值始终是默认值
枚举值不能重复,除非使用 option allow_alias = true 选项来开启别名:
enum EnumAllowingAlias {
option allow_alias = true;
UNKNOWN = 0;
STARTED = 1;
RUNNING = 1;.
}
枚举定义在一 个消息内部或消息外部都是可以的,如果枚举是 定义在 message 内部,而其他message又想使用,那么可以通过 MessageType.EnumType 的方式引用

(5).定义RPC服务

如果需要将message与 RPC一起使用,则可以在 .proto 文件中 定义RPC服务接口,protobuf编译器将根据选择的语言生成RPC接口代码,示例如下:
  1.  
    //定义RPC服务
  2.  
    service HelloService {
  3.  
        rpc Hello (Person)returns (Person);
  4.  
    }
定义一个RPC的服务
  1.  
    syntax = "proto3";
  2.  
     
  3.  
    option go_package = "./sayService";
  4.  
     
  5.  
    service sayService {
  6.  
        rpc SayHello(HelloRequest) returns (HelloRes)
  7.  
    }
  8.  
     
  9.  
    message HelloRequest {
  10.  
        string name = 1;
  11.  
    }
  12.  
     
  13.  
    message HelloRes {
  14.  
        string message = 1;
  15.  
    }
学新通
生成go文件命令:
生成 带RPC服务相关的需要使用以下命令
protoc --go_out=plugins=grpc:. *.proto

(6).案例总结

  1.  
    syntax = "proto3";
  2.  
     
  3.  
    //声明是为了防止不同项目之间的命名冲突,编译生成的类将被放置在一个与 package 名相同的命名空间中
  4.  
    package tutorial;
  5.  
     
  6.  
    message Student {
  7.  
    // 字段编号:消息定义中的每个字段都有一个唯一的编号,这些字段编号用于以二进制格式标识您的字段,一旦您的消息类型被使用,就不应该被更改
  8.  
    uint64 id = 1;
  9.  
    string name = 2;
  10.  
    // singular修饰符修饰的字段可以是0次或者1次,但是当定制协议,用该修饰符修饰的字段都报错
  11.  
    // singular string email = 3;
  12.  
    string email = 3;
  13.  
     
  14.  
    enum PhoneType {
  15.  
    MOBILE = 0; //proto3版本中,首成员必须为0,成员不应有相同的值
  16.  
    HOME = 1;
  17.  
    }
  18.  
     
  19.  
    message PhoneNumber {
  20.  
    string number = 1;
  21.  
    PhoneType type = 2;
  22.  
    }
  23.  
    // repeated: 该字段可以重复任意次数(包括零次),重复值的顺序将被保留
  24.  
    repeated PhoneNumber phone = 4;
  25.  
    }
学新通
  1. protobuf基本编译

protobuf 编译是通过 编译器protoc进行的,通过这个编译器,可以把.proto文件生成
go,Java,Python,C , Ruby, JavaNano, Objective-C,或者C# 代码,生成命令如下:
protoc --proto_path= IMPORT_PATH --go_out= DST_DIR path/to/file.proto
  • --proto_path=IMPORT_PATH,IMPORT_PATH是 .proto 文件所在的路径,如果忽略则默认当前目录,如果有多个目录则可以多次调用--proto_path,它们将会顺序的被访问并执行导入

  • --go_out=DST_DIR, 指定了生成的go语言代码文件放入的文件夹

  • 允许使用 protoc --go_out=./ *.proto 的方式一次性编译多个 .proto 文件

  • go语言编译时,protobuf 编译器会把 .proto 文件编译成 .pd.go 文件

一般在使用的时候都是使用下面这种简单的命令
protoc --go_out=./ *.proto

然后给这个 .proto 文件中添加一个RPC服务,再次进行编译,发现生成的go文件没有发生变化,这是因为世界上的RPC实现有很多种,protoc编译器并不知道该如何为HelloService服务生成代码,不过在protoc-gen-go内部已经集成了一个叫grpc的插件,可以针对grpc生成代码:

protoc --go_out=plugins=grpc:. *.proto
  1. protobuf 序列化反序列化

(1).新建proto/test.proto

  1.  
    syntax = "proto3";
  2.  
    option go_package = "./protoService";
  3.  
    message Userinfo {
  4.  
    string name = 1;
  5.  
    int32 age = 2;
  6.  
    repeated string hobby = 3;
  7.  
    PhoneType phone=4;
  8.  
    }
  9.  
     
  10.  
    //enum为关键字,作用为定义一种枚举类型
  11.  
    enum PhoneType {
  12.  
    MOBILE = 0;
  13.  
    HOME = 1;
  14.  
    WORK = 2;
  15.  
    }
学新通

(2).命令运行,生成.go文件

  1.  
    protoc --go_out=./ *.proto //一般情况下使用这个命令
  2.  
    protoc --go_out=plugins=grpc:. *.proto //有RPC服务的情况下使用这个命令

生成的.go文件如下图所示:

学新通

在这里使用了谷歌.golang.org/protobuf下相关函数,则需要引入对应的插件进行操作,命令如下:

学新通

如果protoService/test.pd.go中的protobuf还是没有被引入,图示:

学新通

则找到go mod tidy 下载的谷歌.golang.org,把protobuf复制到src下,如图示:

学新通
学新通

这样protoServe/test.pb.go中的goole相关插件就引入了,test.pb.go中的protobuf变绿,成功了:

学新通

main.go中实现序列化和反序列化

  1.  
    package main
  2.  
     
  3.  
    import (
  4.  
    "fmt"
  5.  
    "go_code/micro/protoc/protoService"
  6.  
    "谷歌.golang.org/protobuf/proto"
  7.  
    )
  8.  
     
  9.  
    func main() {
  10.  
        //初始化并赋值
  11.  
    u := &protoService.Userinfo{
  12.  
    Name: "zhangsan",
  13.  
    Age: 20,
  14.  
    Hobby: []string{"吃饭", "睡觉", "写代码"},
  15.  
    }
  16.  
    fmt.Println(u.GetHobby())
  17.  
    // proto.Marshald对protoBufer进行序列化
  18.  
    data, err1 := proto.Marshal(u)
  19.  
    if err1 != nil {
  20.  
    fmt.Println(err1)
  21.  
    }
  22.  
    fmt.Println(data)
  23.  
     
  24.  
    //proto.Unmarshal可以对protoBufer进行反序列化
  25.  
    info := protoService.Userinfo{}
  26.  
    err2 := proto.Unmarshal(data, &info)
  27.  
    if err2 != nil {
  28.  
    fmt.Println(err2)
  29.  
    }
  30.  
     
  31.  
    fmt.Printf("%#v", info)
  32.  
    fmt.Println(info.GetHobby())
  33.  
    }
学新通

效果如下图所示:

学新通
  1. protobuf案例演示

(1).案例1

userinfo.proto
用户信息相关proto:
使用了数据类型 string, int, repeated,enum等
  1.  
    syntax = "proto3"; //版本
  2.  
    //./userService:在./userService文件夹中生成文件
  3.  
    option go_package = "./userService";
  4.  
    //注意:写完一行以后要注意 ;
  5.  
    message userinfo{
  6.  
    string username =1; //类型 字段 = 数字(位置)
  7.  
    int32 age =2;
  8.  
    PhoneType type=3;
  9.  
    repeated string hobby=4;
  10.  
    }
  11.  
     
  12.  
    //enum为关键字,作用为定义一种枚举类型
  13.  
    enum PhoneType {
  14.  
    MOBILE = 0;
  15.  
    HOME = 1;
  16.  
    WORK = 2;
  17.  
    }
  18.  
     
  19.  
    //编译的命令:protoc --go_out=./ *.proto
学新通
userService/userinfo.pd.go
使用:protoc --go_out=./ *.proto生成的.go文件
  1.  
    // Code generated by protoc-gen-go. DO NOT EDIT.
  2.  
    // versions:
  3.  
    // protoc-gen-go v1.26.0
  4.  
    // protoc v3.20.0
  5.  
    // source: userinfo.proto
  6.  
     
  7.  
    package userService
  8.  
     
  9.  
    import (
  10.  
    protoreflect "谷歌.golang.org/protobuf/reflect/protoreflect"
  11.  
    protoimpl "谷歌.golang.org/protobuf/runtime/protoimpl"
  12.  
    reflect "reflect"
  13.  
    sync "sync"
  14.  
    )
  15.  
     
  16.  
    const (
  17.  
    // Verify that this generated code is sufficiently up-to-date.
  18.  
    _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
  19.  
    // Verify that runtime/protoimpl is sufficiently up-to-date.
  20.  
    _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
  21.  
    )
  22.  
     
  23.  
    //enum为关键字,作用为定义一种枚举类型
  24.  
    type PhoneType int32
  25.  
     
  26.  
    const (
  27.  
    PhoneType_MOBILE PhoneType = 0
  28.  
    PhoneType_HOME PhoneType = 1
  29.  
    PhoneType_WORK PhoneType = 2
  30.  
    )
  31.  
     
  32.  
    // Enum value maps for PhoneType.
  33.  
    var (
  34.  
    PhoneType_name = map[int32]string{
  35.  
    0: "MOBILE",
  36.  
    1: "HOME",
  37.  
    2: "WORK",
  38.  
    }
  39.  
    PhoneType_value = map[string]int32{
  40.  
    "MOBILE": 0,
  41.  
    "HOME": 1,
  42.  
    "WORK": 2,
  43.  
    }
  44.  
    )
  45.  
     
  46.  
    func (x PhoneType) Enum() *PhoneType {
  47.  
    p := new(PhoneType)
  48.  
    *p = x
  49.  
    return p
  50.  
    }
  51.  
     
  52.  
    func (x PhoneType) String() string {
  53.  
    return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
  54.  
    }
  55.  
     
  56.  
    func (PhoneType) Descriptor() protoreflect.EnumDescriptor {
  57.  
    return file_userinfo_proto_enumTypes[0].Descriptor()
  58.  
    }
  59.  
     
  60.  
    func (PhoneType) Type() protoreflect.EnumType {
  61.  
    return &file_userinfo_proto_enumTypes[0]
  62.  
    }
  63.  
     
  64.  
    func (x PhoneType) Number() protoreflect.EnumNumber {
  65.  
    return protoreflect.EnumNumber(x)
  66.  
    }
  67.  
     
  68.  
    // Deprecated: Use PhoneType.Descriptor instead.
  69.  
    func (PhoneType) EnumDescriptor() ([]byte, []int) {
  70.  
    return file_userinfo_proto_rawDescGZIP(), []int{0}
  71.  
    }
  72.  
     
  73.  
    //注意:写完一行以后要注意 ;
  74.  
    type Userinfo struct {
  75.  
    state protoimpl.MessageState
  76.  
    sizeCache protoimpl.SizeCache
  77.  
    unknownFields protoimpl.UnknownFields
  78.  
     
  79.  
    Username string `protobuf:"bytes,1,opt,name=username,proto3" json:"username,omitempty"`
  80.  
    Age int32 `protobuf:"varint,2,opt,name=age,proto3" json:"age,omitempty"`
  81.  
    Type PhoneType `protobuf:"varint,3,opt,name=type,proto3,enum=PhoneType" json:"type,omitempty"`
  82.  
    Hobby []string `protobuf:"bytes,4,rep,name=hobby,proto3" json:"hobby,omitempty"`
  83.  
    }
  84.  
     
  85.  
    func (x *Userinfo) Reset() {
  86.  
    *x = Userinfo{}
  87.  
    if protoimpl.UnsafeEnabled {
  88.  
    mi := &file_userinfo_proto_msgTypes[0]
  89.  
    ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
  90.  
    ms.StoreMessageInfo(mi)
  91.  
    }
  92.  
    }
  93.  
     
  94.  
    func (x *Userinfo) String() string {
  95.  
    return protoimpl.X.MessageStringOf(x)
  96.  
    }
  97.  
     
  98.  
    func (*Userinfo) ProtoMessage() {}
  99.  
     
  100.  
    func (x *Userinfo) ProtoReflect() protoreflect.Message {
  101.  
    mi := &file_userinfo_proto_msgTypes[0]
  102.  
    if protoimpl.UnsafeEnabled && x != nil {
  103.  
    ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
  104.  
    if ms.LoadMessageInfo() == nil {
  105.  
    ms.StoreMessageInfo(mi)
  106.  
    }
  107.  
    return ms
  108.  
    }
  109.  
    return mi.MessageOf(x)
  110.  
    }
  111.  
     
  112.  
    // Deprecated: Use Userinfo.ProtoReflect.Descriptor instead.
  113.  
    func (*Userinfo) Descriptor() ([]byte, []int) {
  114.  
    return file_userinfo_proto_rawDescGZIP(), []int{0}
  115.  
    }
  116.  
     
  117.  
    func (x *Userinfo) GetUsername() string {
  118.  
    if x != nil {
  119.  
    return x.Username
  120.  
    }
  121.  
    return ""
  122.  
    }
  123.  
     
  124.  
    func (x *Userinfo) GetAge() int32 {
  125.  
    if x != nil {
  126.  
    return x.Age
  127.  
    }
  128.  
    return 0
  129.  
    }
  130.  
     
  131.  
    func (x *Userinfo) GetType() PhoneType {
  132.  
    if x != nil {
  133.  
    return x.Type
  134.  
    }
  135.  
    return PhoneType_MOBILE
  136.  
    }
  137.  
     
  138.  
    func (x *Userinfo) GetHobby() []string {
  139.  
    if x != nil {
  140.  
    return x.Hobby
  141.  
    }
  142.  
    return nil
  143.  
    }
  144.  
     
  145.  
    var File_userinfo_proto protoreflect.FileDescriptor
  146.  
     
  147.  
    var file_userinfo_proto_rawDesc = []byte{
  148.  
    0x0a, 0x0e, 0x75, 0x73, 0x65, 0x72, 0x69, 0x6e, 0x66, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
  149.  
    0x22, 0x6e, 0x0a, 0x08, 0x75, 0x73, 0x65, 0x72, 0x69, 0x6e, 0x66, 0x6f, 0x12, 0x1a, 0x0a, 0x08,
  150.  
    0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08,
  151.  
    0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x61, 0x67, 0x65, 0x18,
  152.  
    0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x61, 0x67, 0x65, 0x12, 0x1e, 0x0a, 0x04, 0x74, 0x79,
  153.  
    0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x0a, 0x2e, 0x50, 0x68, 0x6f, 0x6e, 0x65,
  154.  
    0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x68, 0x6f,
  155.  
    0x62, 0x62, 0x79, 0x18, 0x04, 0x20, 0x03, 0x28, 0x09, 0x52, 0x05, 0x68, 0x6f, 0x62, 0x62, 0x79,
  156.  
    0x2a, 0x2b, 0x0a, 0x09, 0x50, 0x68, 0x6f, 0x6e, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0a, 0x0a,
  157.  
    0x06, 0x4d, 0x4f, 0x42, 0x49, 0x4c, 0x45, 0x10, 0x00, 0x12, 0x08, 0x0a, 0x04, 0x48, 0x4f, 0x4d,
  158.  
    0x45, 0x10, 0x01, 0x12, 0x08, 0x0a, 0x04, 0x57, 0x4f, 0x52, 0x4b, 0x10, 0x02, 0x42, 0x0f, 0x5a,
  159.  
    0x0d, 0x2e, 0x2f, 0x75, 0x73, 0x65, 0x72, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x62, 0x06,
  160.  
    0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
  161.  
    }
  162.  
     
  163.  
    var (
  164.  
    file_userinfo_proto_rawDescOnce sync.Once
  165.  
    file_userinfo_proto_rawDescData = file_userinfo_proto_rawDesc
  166.  
    )
  167.  
     
  168.  
    func file_userinfo_proto_rawDescGZIP() []byte {
  169.  
    file_userinfo_proto_rawDescOnce.Do(func() {
  170.  
    file_userinfo_proto_rawDescData = protoimpl.X.CompressGZIP(file_userinfo_proto_rawDescData)
  171.  
    })
  172.  
    return file_userinfo_proto_rawDescData
  173.  
    }
  174.  
     
  175.  
    var file_userinfo_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
  176.  
    var file_userinfo_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
  177.  
    var file_userinfo_proto_goTypes = []interface{}{
  178.  
    (PhoneType)(0), // 0: PhoneType
  179.  
    (*Userinfo)(nil), // 1: userinfo
  180.  
    }
  181.  
    var file_userinfo_proto_depIdxs = []int32{
  182.  
    0, // 0: userinfo.type:type_name -> PhoneType
  183.  
    1, // [1:1] is the sub-list for method output_type
  184.  
    1, // [1:1] is the sub-list for method input_type
  185.  
    1, // [1:1] is the sub-list for extension type_name
  186.  
    1, // [1:1] is the sub-list for extension extendee
  187.  
    0, // [0:1] is the sub-list for field type_name
  188.  
    }
  189.  
     
  190.  
    func init() { file_userinfo_proto_init() }
  191.  
    func file_userinfo_proto_init() {
  192.  
    if File_userinfo_proto != nil {
  193.  
    return
  194.  
    }
  195.  
    if !protoimpl.UnsafeEnabled {
  196.  
    file_userinfo_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
  197.  
    switch v := v.(*Userinfo); i {
  198.  
    case 0:
  199.  
    return &v.state
  200.  
    case 1:
  201.  
    return &v.sizeCache
  202.  
    case 2:
  203.  
    return &v.unknownFields
  204.  
    default:
  205.  
    return nil
  206.  
    }
  207.  
    }
  208.  
    }
  209.  
    type x struct{}
  210.  
    out := protoimpl.TypeBuilder{
  211.  
    File: protoimpl.DescBuilder{
  212.  
    GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
  213.  
    RawDescriptor: file_userinfo_proto_rawDesc,
  214.  
    NumEnums: 1,
  215.  
    NumMessages: 1,
  216.  
    NumExtensions: 0,
  217.  
    NumServices: 0,
  218.  
    },
  219.  
    GoTypes: file_userinfo_proto_goTypes,
  220.  
    DependencyIndexes: file_userinfo_proto_depIdxs,
  221.  
    EnumInfos: file_userinfo_proto_enumTypes,
  222.  
    MessageInfos: file_userinfo_proto_msgTypes,
  223.  
    }.Build()
  224.  
    File_userinfo_proto = out.File
  225.  
    file_userinfo_proto_rawDesc = nil
  226.  
    file_userinfo_proto_goTypes = nil
  227.  
    file_userinfo_proto_depIdxs = nil
  228.  
    }
学新通
main.go
序列化反序列化实现
  1.  
    package main
  2.  
     
  3.  
    import (
  4.  
    "fmt"
  5.  
    "proto_deom/proto/userService"
  6.  
    "谷歌.golang.org/protobuf/proto"
  7.  
    )
  8.  
     
  9.  
    func main() {
  10.  
    u := &userService.Userinfo{
  11.  
    Username: "张三",
  12.  
    Age: 20,
  13.  
    Hobby: []string{"吃饭", "睡觉", "写代码"},
  14.  
    }
  15.  
    // fmt.Println(u)
  16.  
     
  17.  
    fmt.Println(u.GetType())
  18.  
    fmt.Println(u.GetUsername())
  19.  
    fmt.Println(u.GetHobby())
  20.  
    //Protobuf的序列化
  21.  
    data, _ := proto.Marshal(u)
  22.  
    fmt.Println(data)
  23.  
     
  24.  
    //Protobuf的反序列化
  25.  
    user := userService.Userinfo{}
  26.  
    proto.Unmarshal(data, &user)
  27.  
    fmt.Printf("%#v\n", user)
  28.  
    fmt.Println(user.GetHobby())
  29.  
    }
学新通

(2).案例2

order.proto
订单相关:
相关数据类型的使用, message嵌套使用
  1.  
    syntax = "proto3";
  2.  
    option go_package = "./orderService";
  3.  
     
  4.  
    message Order{
  5.  
    int64 id =1;
  6.  
    double price =2;
  7.  
    string name =3;
  8.  
    string tel=4;
  9.  
    string address=5;
  10.  
    string addTime=6;
  11.  
    //message可以嵌套
  12.  
    // message OrderItem{
  13.  
    // int64 goodsId =1;
  14.  
    // string title=2;
  15.  
    // double price =3;
  16.  
    // int32 num =4;
  17.  
    // }
  18.  
    OrderItem Orderitem =7;
  19.  
    }
  20.  
     
  21.  
    message OrderItem{
  22.  
    int64 goodsId =1;
  23.  
    string title=2;
  24.  
    double price =3;
  25.  
    int32 num =4;
  26.  
    }
  27.  
     
  28.  
    // protoc --go_out=./ *.proto
学新通
orderService/order.pb.go
  1.  
    // Code generated by protoc-gen-go. DO NOT EDIT.
  2.  
    // versions:
  3.  
    // protoc-gen-go v1.26.0
  4.  
    // protoc v3.20.0
  5.  
    // source: order.proto
  6.  
     
  7.  
    package orderService
  8.  
     
  9.  
    import (
  10.  
    protoreflect "谷歌.golang.org/protobuf/reflect/protoreflect"
  11.  
    protoimpl "谷歌.golang.org/protobuf/runtime/protoimpl"
  12.  
    reflect "reflect"
  13.  
    sync "sync"
  14.  
    )
  15.  
     
  16.  
    const (
  17.  
    // Verify that this generated code is sufficiently up-to-date.
  18.  
    _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
  19.  
    // Verify that runtime/protoimpl is sufficiently up-to-date.
  20.  
    _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
  21.  
    )
  22.  
     
  23.  
    type Order struct {
  24.  
    state protoimpl.MessageState
  25.  
    sizeCache protoimpl.SizeCache
  26.  
    unknownFields protoimpl.UnknownFields
  27.  
     
  28.  
    Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
  29.  
    Price float64 `protobuf:"fixed64,2,opt,name=price,proto3" json:"price,omitempty"`
  30.  
    Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"`
  31.  
    Tel string `protobuf:"bytes,4,opt,name=tel,proto3" json:"tel,omitempty"`
  32.  
    Address string `protobuf:"bytes,5,opt,name=address,proto3" json:"address,omitempty"`
  33.  
    AddTime string `protobuf:"bytes,6,opt,name=addTime,proto3" json:"addTime,omitempty"`
  34.  
    //message可以嵌套
  35.  
    // message OrderItem{
  36.  
    // int64 goodsId =1;
  37.  
    // string title=2;
  38.  
    // double price =3;
  39.  
    // int32 num =4;
  40.  
    // }
  41.  
    Orderitem *OrderItem `protobuf:"bytes,7,opt,name=Orderitem,proto3" json:"Orderitem,omitempty"`
  42.  
    }
  43.  
     
  44.  
    func (x *Order) Reset() {
  45.  
    *x = Order{}
  46.  
    if protoimpl.UnsafeEnabled {
  47.  
    mi := &file_order_proto_msgTypes[0]
  48.  
    ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
  49.  
    ms.StoreMessageInfo(mi)
  50.  
    }
  51.  
    }
  52.  
     
  53.  
    func (x *Order) String() string {
  54.  
    return protoimpl.X.MessageStringOf(x)
  55.  
    }
  56.  
     
  57.  
    func (*Order) ProtoMessage() {}
  58.  
     
  59.  
    func (x *Order) ProtoReflect() protoreflect.Message {
  60.  
    mi := &file_order_proto_msgTypes[0]
  61.  
    if protoimpl.UnsafeEnabled && x != nil {
  62.  
    ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
  63.  
    if ms.LoadMessageInfo() == nil {
  64.  
    ms.StoreMessageInfo(mi)
  65.  
    }
  66.  
    return ms
  67.  
    }
  68.  
    return mi.MessageOf(x)
  69.  
    }
  70.  
     
  71.  
    // Deprecated: Use Order.ProtoReflect.Descriptor instead.
  72.  
    func (*Order) Descriptor() ([]byte, []int) {
  73.  
    return file_order_proto_rawDescGZIP(), []int{0}
  74.  
    }
  75.  
     
  76.  
    func (x *Order) GetId() int64 {
  77.  
    if x != nil {
  78.  
    return x.Id
  79.  
    }
  80.  
    return 0
  81.  
    }
  82.  
     
  83.  
    func (x *Order) GetPrice() float64 {
  84.  
    if x != nil {
  85.  
    return x.Price
  86.  
    }
  87.  
    return 0
  88.  
    }
  89.  
     
  90.  
    func (x *Order) GetName() string {
  91.  
    if x != nil {
  92.  
    return x.Name
  93.  
    }
  94.  
    return ""
  95.  
    }
  96.  
     
  97.  
    func (x *Order) GetTel() string {
  98.  
    if x != nil {
  99.  
    return x.Tel
  100.  
    }
  101.  
    return ""
  102.  
    }
  103.  
     
  104.  
    func (x *Order) GetAddress() string {
  105.  
    if x != nil {
  106.  
    return x.Address
  107.  
    }
  108.  
    return ""
  109.  
    }
  110.  
     
  111.  
    func (x *Order) GetAddTime() string {
  112.  
    if x != nil {
  113.  
    return x.AddTime
  114.  
    }
  115.  
    return ""
  116.  
    }
  117.  
     
  118.  
    func (x *Order) GetOrderitem() *OrderItem {
  119.  
    if x != nil {
  120.  
    return x.Orderitem
  121.  
    }
  122.  
    return nil
  123.  
    }
  124.  
     
  125.  
    type OrderItem struct {
  126.  
    state protoimpl.MessageState
  127.  
    sizeCache protoimpl.SizeCache
  128.  
    unknownFields protoimpl.UnknownFields
  129.  
     
  130.  
    GoodsId int64 `protobuf:"varint,1,opt,name=goodsId,proto3" json:"goodsId,omitempty"`
  131.  
    Title string `protobuf:"bytes,2,opt,name=title,proto3" json:"title,omitempty"`
  132.  
    Price float64 `protobuf:"fixed64,3,opt,name=price,proto3" json:"price,omitempty"`
  133.  
    Num int32 `protobuf:"varint,4,opt,name=num,proto3" json:"num,omitempty"`
  134.  
    }
  135.  
     
  136.  
    func (x *OrderItem) Reset() {
  137.  
    *x = OrderItem{}
  138.  
    if protoimpl.UnsafeEnabled {
  139.  
    mi := &file_order_proto_msgTypes[1]
  140.  
    ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
  141.  
    ms.StoreMessageInfo(mi)
  142.  
    }
  143.  
    }
  144.  
     
  145.  
    func (x *OrderItem) String() string {
  146.  
    return protoimpl.X.MessageStringOf(x)
  147.  
    }
  148.  
     
  149.  
    func (*OrderItem) ProtoMessage() {}
  150.  
     
  151.  
    func (x *OrderItem) ProtoReflect() protoreflect.Message {
  152.  
    mi := &file_order_proto_msgTypes[1]
  153.  
    if protoimpl.UnsafeEnabled && x != nil {
  154.  
    ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
  155.  
    if ms.LoadMessageInfo() == nil {
  156.  
    ms.StoreMessageInfo(mi)
  157.  
    }
  158.  
    return ms
  159.  
    }
  160.  
    return mi.MessageOf(x)
  161.  
    }
  162.  
     
  163.  
    // Deprecated: Use OrderItem.ProtoReflect.Descriptor instead.
  164.  
    func (*OrderItem) Descriptor() ([]byte, []int) {
  165.  
    return file_order_proto_rawDescGZIP(), []int{1}
  166.  
    }
  167.  
     
  168.  
    func (x *OrderItem) GetGoodsId() int64 {
  169.  
    if x != nil {
  170.  
    return x.GoodsId
  171.  
    }
  172.  
    return 0
  173.  
    }
  174.  
     
  175.  
    func (x *OrderItem) GetTitle() string {
  176.  
    if x != nil {
  177.  
    return x.Title
  178.  
    }
  179.  
    return ""
  180.  
    }
  181.  
     
  182.  
    func (x *OrderItem) GetPrice() float64 {
  183.  
    if x != nil {
  184.  
    return x.Price
  185.  
    }
  186.  
    return 0
  187.  
    }
  188.  
     
  189.  
    func (x *OrderItem) GetNum() int32 {
  190.  
    if x != nil {
  191.  
    return x.Num
  192.  
    }
  193.  
    return 0
  194.  
    }
  195.  
     
  196.  
    var File_order_proto protoreflect.FileDescriptor
  197.  
     
  198.  
    var file_order_proto_rawDesc = []byte{
  199.  
    0x0a, 0x0b, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xb1, 0x01,
  200.  
    0x0a, 0x05, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20,
  201.  
    0x01, 0x28, 0x03, 0x52, 0x02, 0x69, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65,
  202.  
    0x18, 0x02, 0x20, 0x01, 0x28, 0x01, 0x52, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65, 0x12, 0x12, 0x0a,
  203.  
    0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d,
  204.  
    0x65, 0x12, 0x10, 0x0a, 0x03, 0x74, 0x65, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03,
  205.  
    0x74, 0x65, 0x6c, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x05,
  206.  
    0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x18, 0x0a,
  207.  
    0x07, 0x61, 0x64, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07,
  208.  
    0x61, 0x64, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x28, 0x0a, 0x09, 0x4f, 0x72, 0x64, 0x65, 0x72,
  209.  
    0x69, 0x74, 0x65, 0x6d, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0a, 0x2e, 0x4f, 0x72, 0x64,
  210.  
    0x65, 0x72, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x09, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x69, 0x74, 0x65,
  211.  
    0x6d, 0x22, 0x63, 0x0a, 0x09, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x49, 0x74, 0x65, 0x6d, 0x12, 0x18,
  212.  
    0x0a, 0x07, 0x67, 0x6f, 0x6f, 0x64, 0x73, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52,
  213.  
    0x07, 0x67, 0x6f, 0x6f, 0x64, 0x73, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x69, 0x74, 0x6c,
  214.  
    0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x12, 0x14,
  215.  
    0x0a, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x01, 0x52, 0x05, 0x70,
  216.  
    0x72, 0x69, 0x63, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x6e, 0x75, 0x6d, 0x18, 0x04, 0x20, 0x01, 0x28,
  217.  
    0x05, 0x52, 0x03, 0x6e, 0x75, 0x6d, 0x42, 0x10, 0x5a, 0x0e, 0x2e, 0x2f, 0x6f, 0x72, 0x64, 0x65,
  218.  
    0x72, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
  219.  
    }
  220.  
     
  221.  
    var (
  222.  
    file_order_proto_rawDescOnce sync.Once
  223.  
    file_order_proto_rawDescData = file_order_proto_rawDesc
  224.  
    )
  225.  
     
  226.  
    func file_order_proto_rawDescGZIP() []byte {
  227.  
    file_order_proto_rawDescOnce.Do(func() {
  228.  
    file_order_proto_rawDescData = protoimpl.X.CompressGZIP(file_order_proto_rawDescData)
  229.  
    })
  230.  
    return file_order_proto_rawDescData
  231.  
    }
  232.  
     
  233.  
    var file_order_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
  234.  
    var file_order_proto_goTypes = []interface{}{
  235.  
    (*Order)(nil), // 0: Order
  236.  
    (*OrderItem)(nil), // 1: OrderItem
  237.  
    }
  238.  
    var file_order_proto_depIdxs = []int32{
  239.  
    1, // 0: Order.Orderitem:type_name -> OrderItem
  240.  
    1, // [1:1] is the sub-list for method output_type
  241.  
    1, // [1:1] is the sub-list for method input_type
  242.  
    1, // [1:1] is the sub-list for extension type_name
  243.  
    1, // [1:1] is the sub-list for extension extendee
  244.  
    0, // [0:1] is the sub-list for field type_name
  245.  
    }
  246.  
     
  247.  
    func init() { file_order_proto_init() }
  248.  
    func file_order_proto_init() {
  249.  
    if File_order_proto != nil {
  250.  
    return
  251.  
    }
  252.  
    if !protoimpl.UnsafeEnabled {
  253.  
    file_order_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
  254.  
    switch v := v.(*Order); i {
  255.  
    case 0:
  256.  
    return &v.state
  257.  
    case 1:
  258.  
    return &v.sizeCache
  259.  
    case 2:
  260.  
    return &v.unknownFields
  261.  
    default:
  262.  
    return nil
  263.  
    }
  264.  
    }
  265.  
    file_order_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
  266.  
    switch v := v.(*OrderItem); i {
  267.  
    case 0:
  268.  
    return &v.state
  269.  
    case 1:
  270.  
    return &v.sizeCache
  271.  
    case 2:
  272.  
    return &v.unknownFields
  273.  
    default:
  274.  
    return nil
  275.  
    }
  276.  
    }
  277.  
    }
  278.  
    type x struct{}
  279.  
    out := protoimpl.TypeBuilder{
  280.  
    File: protoimpl.DescBuilder{
  281.  
    GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
  282.  
    RawDescriptor: file_order_proto_rawDesc,
  283.  
    NumEnums: 0,
  284.  
    NumMessages: 2,
  285.  
    NumExtensions: 0,
  286.  
    NumServices: 0,
  287.  
    },
  288.  
    GoTypes: file_order_proto_goTypes,
  289.  
    DependencyIndexes: file_order_proto_depIdxs,
  290.  
    MessageInfos: file_order_proto_msgTypes,
  291.  
    }.Build()
  292.  
    File_order_proto = out.File
  293.  
    file_order_proto_rawDesc = nil
  294.  
    file_order_proto_goTypes = nil
  295.  
    file_order_proto_depIdxs = nil
  296.  
    }
学新通

(3).案例3

goods.proto
RPC服务的定义
  1.  
    syntax = "proto3";
  2.  
    option go_package = "./goodsService";
  3.  
    //RPC接口, 定义RPC服务,生成的是接口
  4.  
    service GoodsService{
  5.  
    rpc AddGoods(AddGoodsReq) returns (AddGoodsRes);
  6.  
    rpc GetGoods(GetGoodsReq) returns (GetGoodsRes);
  7.  
    }
  8.  
    message GoodsMode{
  9.  
    string title =1;
  10.  
    double price =2;
  11.  
    string content =3;
  12.  
    }
  13.  
    //AddGoods相关参数
  14.  
    message AddGoodsReq{
  15.  
    GoodsMode params=1;
  16.  
    }
  17.  
    message AddGoodsRes{
  18.  
    string message =1;
  19.  
    bool success =2;
  20.  
    }
  21.  
    //GetGoods相关参数
  22.  
    message GetGoodsReq{
  23.  
    int32 id =1;
  24.  
    }
  25.  
    message GetGoodsRes{
  26.  
    repeated GoodsMode goodsList=1;
  27.  
    }
  28.  
    /*
  29.  
    protoc --go_out=./ *.proto
  30.  
    有RPC接口使用下面方法生成proto go文件
  31.  
    protoc --go_out=plugins=grpc:. *.proto
  32.  
    */
学新通
goodsService/goods.pb.go
  1.  
    // Code generated by protoc-gen-go. DO NOT EDIT.
  2.  
    // versions:
  3.  
    // protoc-gen-go v1.26.0
  4.  
    // protoc v3.20.0
  5.  
    // source: goods.proto
  6.  
     
  7.  
    package goodsService
  8.  
     
  9.  
    import (
  10.  
    context "context"
  11.  
    grpc "谷歌.golang.org/grpc"
  12.  
    codes "谷歌.golang.org/grpc/codes"
  13.  
    status "谷歌.golang.org/grpc/status"
  14.  
    protoreflect "谷歌.golang.org/protobuf/reflect/protoreflect"
  15.  
    protoimpl "谷歌.golang.org/protobuf/runtime/protoimpl"
  16.  
    reflect "reflect"
  17.  
    sync "sync"
  18.  
    )
  19.  
     
  20.  
    const (
  21.  
    // Verify that this generated code is sufficiently up-to-date.
  22.  
    _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
  23.  
    // Verify that runtime/protoimpl is sufficiently up-to-date.
  24.  
    _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
  25.  
    )
  26.  
     
  27.  
    type AddGoodsReq struct {
  28.  
    state protoimpl.MessageState
  29.  
    sizeCache protoimpl.SizeCache
  30.  
    unknownFields protoimpl.UnknownFields
  31.  
     
  32.  
    Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"`
  33.  
    Price float64 `protobuf:"fixed64,2,opt,name=price,proto3" json:"price,omitempty"`
  34.  
    Content string `protobuf:"bytes,3,opt,name=content,proto3" json:"content,omitempty"`
  35.  
    }
  36.  
     
  37.  
    func (x *AddGoodsReq) Reset() {
  38.  
    *x = AddGoodsReq{}
  39.  
    if protoimpl.UnsafeEnabled {
  40.  
    mi := &file_goods_proto_msgTypes[0]
  41.  
    ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
  42.  
    ms.StoreMessageInfo(mi)
  43.  
    }
  44.  
    }
  45.  
     
  46.  
    func (x *AddGoodsReq) String() string {
  47.  
    return protoimpl.X.MessageStringOf(x)
  48.  
    }
  49.  
     
  50.  
    func (*AddGoodsReq) ProtoMessage() {}
  51.  
     
  52.  
    func (x *AddGoodsReq) ProtoReflect() protoreflect.Message {
  53.  
    mi := &file_goods_proto_msgTypes[0]
  54.  
    if protoimpl.UnsafeEnabled && x != nil {
  55.  
    ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
  56.  
    if ms.LoadMessageInfo() == nil {
  57.  
    ms.StoreMessageInfo(mi)
  58.  
    }
  59.  
    return ms
  60.  
    }
  61.  
    return mi.MessageOf(x)
  62.  
    }
  63.  
     
  64.  
    // Deprecated: Use AddGoodsReq.ProtoReflect.Descriptor instead.
  65.  
    func (*AddGoodsReq) Descriptor() ([]byte, []int) {
  66.  
    return file_goods_proto_rawDescGZIP(), []int{0}
  67.  
    }
  68.  
     
  69.  
    func (x *AddGoodsReq) GetTitle() string {
  70.  
    if x != nil {
  71.  
    return x.Title
  72.  
    }
  73.  
    return ""
  74.  
    }
  75.  
     
  76.  
    func (x *AddGoodsReq) GetPrice() float64 {
  77.  
    if x != nil {
  78.  
    return x.Price
  79.  
    }
  80.  
    return 0
  81.  
    }
  82.  
     
  83.  
    func (x *AddGoodsReq) GetContent() string {
  84.  
    if x != nil {
  85.  
    return x.Content
  86.  
    }
  87.  
    return ""
  88.  
    }
  89.  
     
  90.  
    type AddGoodsRes struct {
  91.  
    state protoimpl.MessageState
  92.  
    sizeCache protoimpl.SizeCache
  93.  
    unknownFields protoimpl.UnknownFields
  94.  
     
  95.  
    Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"`
  96.  
    Success bool `protobuf:"varint,2,opt,name=success,proto3" json:"success,omitempty"`
  97.  
    }
  98.  
     
  99.  
    func (x *AddGoodsRes) Reset() {
  100.  
    *x = AddGoodsRes{}
  101.  
    if protoimpl.UnsafeEnabled {
  102.  
    mi := &file_goods_proto_msgTypes[1]
  103.  
    ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
  104.  
    ms.StoreMessageInfo(mi)
  105.  
    }
  106.  
    }
  107.  
     
  108.  
    func (x *AddGoodsRes) String() string {
  109.  
    return protoimpl.X.MessageStringOf(x)
  110.  
    }
  111.  
     
  112.  
    func (*AddGoodsRes) ProtoMessage() {}
  113.  
     
  114.  
    func (x *AddGoodsRes) ProtoReflect() protoreflect.Message {
  115.  
    mi := &file_goods_proto_msgTypes[1]
  116.  
    if protoimpl.UnsafeEnabled && x != nil {
  117.  
    ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
  118.  
    if ms.LoadMessageInfo() == nil {
  119.  
    ms.StoreMessageInfo(mi)
  120.  
    }
  121.  
    return ms
  122.  
    }
  123.  
    return mi.MessageOf(x)
  124.  
    }
  125.  
     
  126.  
    // Deprecated: Use AddGoodsRes.ProtoReflect.Descriptor instead.
  127.  
    func (*AddGoodsRes) Descriptor() ([]byte, []int) {
  128.  
    return file_goods_proto_rawDescGZIP(), []int{1}
  129.  
    }
  130.  
     
  131.  
    func (x *AddGoodsRes) GetMessage() string {
  132.  
    if x != nil {
  133.  
    return x.Message
  134.  
    }
  135.  
    return ""
  136.  
    }
  137.  
     
  138.  
    func (x *AddGoodsRes) GetSuccess() bool {
  139.  
    if x != nil {
  140.  
    return x.Success
  141.  
    }
  142.  
    return false
  143.  
    }
  144.  
     
  145.  
    var File_goods_proto protoreflect.FileDescriptor
  146.  
     
  147.  
    var file_goods_proto_rawDesc = []byte{
  148.  
    0x0a, 0x0b, 0x67, 0x6f, 0x6f, 0x64, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x53, 0x0a,
  149.  
    0x0b, 0x41, 0x64, 0x64, 0x47, 0x6f, 0x6f, 0x64, 0x73, 0x52, 0x65, 0x71, 0x12, 0x14, 0x0a, 0x05,
  150.  
    0x74, 0x69, 0x74, 0x6c, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x69, 0x74,
  151.  
    0x6c, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28,
  152.  
    0x01, 0x52, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74,
  153.  
    0x65, 0x6e, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65,
  154.  
    0x6e, 0x74, 0x22, 0x41, 0x0a, 0x0b, 0x41, 0x64, 0x64, 0x47, 0x6f, 0x6f, 0x64, 0x73, 0x52, 0x65,
  155.  
    0x73, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01,
  156.  
    0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x73,
  157.  
    0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x73, 0x75,
  158.  
    0x63, 0x63, 0x65, 0x73, 0x73, 0x32, 0x36, 0x0a, 0x0c, 0x47, 0x6f, 0x6f, 0x64, 0x73, 0x53, 0x65,
  159.  
    0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x26, 0x0a, 0x08, 0x41, 0x64, 0x64, 0x47, 0x6f, 0x6f, 0x64,
  160.  
    0x73, 0x12, 0x0c, 0x2e, 0x41, 0x64, 0x64, 0x47, 0x6f, 0x6f, 0x64, 0x73, 0x52, 0x65, 0x71, 0x1a,
  161.  
    0x0c, 0x2e, 0x41, 0x64, 0x64, 0x47, 0x6f, 0x6f, 0x64, 0x73, 0x52, 0x65, 0x73, 0x42, 0x10, 0x5a,
  162.  
    0x0e, 0x2e, 0x2f, 0x67, 0x6f, 0x6f, 0x64, 0x73, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x62,
  163.  
    0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
  164.  
    }
  165.  
     
  166.  
    var (
  167.  
    file_goods_proto_rawDescOnce sync.Once
  168.  
    file_goods_proto_rawDescData = file_goods_proto_rawDesc
  169.  
    )
  170.  
     
  171.  
    func file_goods_proto_rawDescGZIP() []byte {
  172.  
    file_goods_proto_rawDescOnce.Do(func() {
  173.  
    file_goods_proto_rawDescData = protoimpl.X.CompressGZIP(file_goods_proto_rawDescData)
  174.  
    })
  175.  
    return file_goods_proto_rawDescData
  176.  
    }
  177.  
     
  178.  
    var file_goods_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
  179.  
    var file_goods_proto_goTypes = []interface{}{
  180.  
    (*AddGoodsReq)(nil), // 0: AddGoodsReq
  181.  
    (*AddGoodsRes)(nil), // 1: AddGoodsRes
  182.  
    }
  183.  
    var file_goods_proto_depIdxs = []int32{
  184.  
    0, // 0: GoodsService.AddGoods:input_type -> AddGoodsReq
  185.  
    1, // 1: GoodsService.AddGoods:output_type -> AddGoodsRes
  186.  
    1, // [1:2] is the sub-list for method output_type
  187.  
    0, // [0:1] is the sub-list for method input_type
  188.  
    0, // [0:0] is the sub-list for extension type_name
  189.  
    0, // [0:0] is the sub-list for extension extendee
  190.  
    0, // [0:0] is the sub-list for field type_name
  191.  
    }
  192.  
     
  193.  
    func init() { file_goods_proto_init() }
  194.  
    func file_goods_proto_init() {
  195.  
    if File_goods_proto != nil {
  196.  
    return
  197.  
    }
  198.  
    if !protoimpl.UnsafeEnabled {
  199.  
    file_goods_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
  200.  
    switch v := v.(*AddGoodsReq); i {
  201.  
    case 0:
  202.  
    return &v.state
  203.  
    case 1:
  204.  
    return &v.sizeCache
  205.  
    case 2:
  206.  
    return &v.unknownFields
  207.  
    default:
  208.  
    return nil
  209.  
    }
  210.  
    }
  211.  
    file_goods_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
  212.  
    switch v := v.(*AddGoodsRes); i {
  213.  
    case 0:
  214.  
    return &v.state
  215.  
    case 1:
  216.  
    return &v.sizeCache
  217.  
    case 2:
  218.  
    return &v.unknownFields
  219.  
    default:
  220.  
    return nil
  221.  
    }
  222.  
    }
  223.  
    }
  224.  
    type x struct{}
  225.  
    out := protoimpl.TypeBuilder{
  226.  
    File: protoimpl.DescBuilder{
  227.  
    GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
  228.  
    RawDescriptor: file_goods_proto_rawDesc,
  229.  
    NumEnums: 0,
  230.  
    NumMessages: 2,
  231.  
    NumExtensions: 0,
  232.  
    NumServices: 1,
  233.  
    },
  234.  
    GoTypes: file_goods_proto_goTypes,
  235.  
    DependencyIndexes: file_goods_proto_depIdxs,
  236.  
    MessageInfos: file_goods_proto_msgTypes,
  237.  
    }.Build()
  238.  
    File_goods_proto = out.File
  239.  
    file_goods_proto_rawDesc = nil
  240.  
    file_goods_proto_goTypes = nil
  241.  
    file_goods_proto_depIdxs = nil
  242.  
    }
  243.  
     
  244.  
    // Reference imports to suppress errors if they are not otherwise used.
  245.  
    var _ context.Context
  246.  
    var _ grpc.ClientConnInterface
  247.  
     
  248.  
    // This is a compile-time assertion to ensure that this generated file
  249.  
    // is compatible with the grpc package it is being compiled against.
  250.  
    const _ = grpc.SupportPackageIsVersion6
  251.  
     
  252.  
    // GoodsServiceClient is the client API for GoodsService service.
  253.  
    //
  254.  
    // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/谷歌.golang.org/grpc#ClientConn.NewStream.
  255.  
    type GoodsServiceClient interface {
  256.  
    AddGoods(ctx context.Context, in *AddGoodsReq, opts ...grpc.CallOption) (*AddGoodsRes, error)
  257.  
    }
  258.  
     
  259.  
    type goodsServiceClient struct {
  260.  
    cc grpc.ClientConnInterface
  261.  
    }
  262.  
     
  263.  
    func NewGoodsServiceClient(cc grpc.ClientConnInterface) GoodsServiceClient {
  264.  
    return &goodsServiceClient{cc}
  265.  
    }
  266.  
     
  267.  
    func (c *goodsServiceClient) AddGoods(ctx context.Context, in *AddGoodsReq, opts ...grpc.CallOption) (*AddGoodsRes, error) {
  268.  
    out := new(AddGoodsRes)
  269.  
    err := c.cc.Invoke(ctx, "/GoodsService/AddGoods", in, out, opts...)
  270.  
    if err != nil {
  271.  
    return nil, err
  272.  
    }
  273.  
    return out, nil
  274.  
    }
  275.  
     
  276.  
    // GoodsServiceServer is the server API for GoodsService service.
  277.  
    type GoodsServiceServer interface {
  278.  
    AddGoods(context.Context, *AddGoodsReq) (*AddGoodsRes, error)
  279.  
    }
  280.  
     
  281.  
    // UnimplementedGoodsServiceServer can be embedded to have forward compatible implementations.
  282.  
    type UnimplementedGoodsServiceServer struct {
  283.  
    }
  284.  
     
  285.  
    func (*UnimplementedGoodsServiceServer) AddGoods(context.Context, *AddGoodsReq) (*AddGoodsRes, error) {
  286.  
    return nil, status.Errorf(codes.Unimplemented, "method AddGoods not implemented")
  287.  
    }
  288.  
     
  289.  
    func RegisterGoodsServiceServer(s *grpc.Server, srv GoodsServiceServer) {
  290.  
    s.RegisterService(&_GoodsService_serviceDesc, srv)
  291.  
    }
  292.  
     
  293.  
    func _GoodsService_AddGoods_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
  294.  
    in := new(AddGoodsReq)
  295.  
    if err := dec(in); err != nil {
  296.  
    return nil, err
  297.  
    }
  298.  
    if interceptor == nil {
  299.  
    return srv.(GoodsServiceServer).AddGoods(ctx, in)
  300.  
    }
  301.  
    info := &grpc.UnaryServerInfo{
  302.  
    Server: srv,
  303.  
    FullMethod: "/GoodsService/AddGoods",
  304.  
    }
  305.  
    handler := func(ctx context.Context, req interface{}) (interface{}, error) {
  306.  
    return srv.(GoodsServiceServer).AddGoods(ctx, req.(*AddGoodsReq))
  307.  
    }
  308.  
    return interceptor(ctx, in, info, handler)
  309.  
    }
  310.  
     
  311.  
    var _GoodsService_serviceDesc = grpc.ServiceDesc{
  312.  
    ServiceName: "GoodsService",
  313.  
    HandlerType: (*GoodsServiceServer)(nil),
  314.  
    Methods: []grpc.MethodDesc{
  315.  
    {
  316.  
    MethodName: "AddGoods",
  317.  
    Handler: _GoodsService_AddGoods_Handler,
  318.  
    },
  319.  
    },
  320.  
    Streams: []grpc.StreamDesc{},
  321.  
    Metadata: "goods.proto",
  322.  
    }
学新通

[上一节][golang 微服务] 2. RPC架构介绍以及通过RPC实现微服务

[下一节][golang 微服务] 4. gRPC介绍,Protobuf结合gRPC 创建微服务

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgfhkci
系列文章
更多 icon
同类精品
更多 icon
继续加载