zoukankan      html  css  js  c++  java
  • 2.Grpc消息定义

    一个简单示例

    syntax ="proto3";//设置默认版本,不写默认为proto2
    
    //1,2,3  是字段的标记 Tag 不表示字段的值
    message FirstMessage{
        int32 id=1;
        string name=2;
        bool is_male=3;
    }

    syntax="proto3";
    
    message Person{
        int32 id=1;
        string name=2;
        float height=3;
        float weight=4;
        bytes avatar=5;
        string email=6;
        bool email_verified=7;
    
        repeated string phone_number=8;//packed
        //表示这些范围的数字/字段要保留。不能对自己或其他开发者所使用,就是占个茅坑
        reserved 9,10,20 to 100, 200 to max; 
        reserved "foo","bar";
    }

    服务器定义和客户端的消息定义,如果服务费端的某个字段没有传值,就会默认使用下面的字段类型的默认值

    枚举里也可以使用 reserved ,repeated

    定义一个枚举

       Gender gender=11;
        enum Gender{
            NOT_SPECIFIED=0;//必须有0
            FEMALE=1;
            MALE=2;
        }

       Gender gender=11;
        enum Gender{
            option allow_alias =true;
            NOT_SPECIFIED=0;//必须有0
            //两个单词都表示女
            FEMALE=1;
            WOMAN=1;
            //两个单词都表示男
            MAN=2;
            MALE=2;
        }

    如果在一个message 中定义的太多,就会影响代码的阅读质量,可以写成类似于类的形式,调用即可

     另外,在message中也可以嵌套定义message

    syntax="proto3";
    
    message Person{

    //使用重复字段repeated修饰 表示一个人可以有多个住址 repeated Address address=13;
    //住址 message Address{ string province=1; string city=2; string zip_code=3; string street=4; string number=5; }
    }

    假设项目较大,恰好有两个message都叫同一个名字,但是目录结构不一样,这时候仅仅靠目录结构不同,是不能避免冲突的,可以使用打包

    在编译的就会自动生成C#的命名空间 namespace My.Project

    package my.project;//C# namespace My.Project

    还可以设置命名空间

    option csharp_namespace ="My.WebApis";

    设置Protocol Buffers编译器

    protoc编译器主要就是用来生成代码的,下载地址

    https://github.com/protocolbuffers/protobuf/releases

    找到对应版本,在这里用的是protoc-3.11.4-win64

    解压,自己找个目录存放起来

    设置环境变量,复制路径(到bin目录:E:protoc-3.11.4-win64in)

    添加到path环境变量

     

     success

    在vscode 中使用命令行

     在终端输入protoc,不行的话重启vscode ,因为设置了环境变量,vscode还没有读取到

    输入protoc后可以自行查看参数

    使用protoc生成C#代码

    protoc --csharp_out=csharp date.proto
  • 相关阅读:
    Vue 2.x windows环境下安装
    VSCODE官网下载缓慢或下载失败 解决办法
    angular cli 降级
    Win10 VS2019 设置 以管理员身份运行
    XSHELL 连接 阿里云ECS实例
    Chrome浏览器跨域设置
    DBeaver 执行 mysql 多条语句报错
    DBeaver 连接MySql 8.0 报错 Public Key Retrieval is not allowed
    DBeaver 连接MySql 8.0报错 Unable to load authentication plugin 'caching_sha2_password'
    Linux系统分区
  • 原文地址:https://www.cnblogs.com/mi21/p/12625991.html
Copyright © 2011-2022 走看看