美文网首页
protobuf使用

protobuf使用

作者: 小李_a98e | 来源:发表于2018-06-05 16:25 被阅读0次

    protobuf的使用

    • protobuf .proto文件 idea安装protobuf插件

       syntax = "proto2";
       package tutorial;
       option java_package = "com.xxx.protobuf";
       option java_outer_classname = "AddressBookProtos";
       message Person {
           required string name = 1;
           required int32 id = 2;
           optional string email = 3;
       /*
           enum PhoneType {
               MOBILE = 0;
               HOME = 1;
               WORK = 2;
           }
       
           message PhoneNumber {
               required string number = 1;
               optional PhoneType type = 2 [default = HOME];
           }
       
           repeated PhoneNumber phones = 4;*/
           required string content = 4;
       }
      

      proto文件详解 https://blog.csdn.net/u014308482/article/details/52958148

    • protoc 指定proto文件生成java代码

        protoc -I=$SRC_DIR --java_out=$DST_DIR $SRC_DIR/addressbook.proto
      
    • 发送消息

        AddressBookProtos.Person.Builder person = AddressBookProtos.Person.newBuilder();
        person.setId(1);
        person.setContent("xxxx");
        person.setEmail("xlfast@foxmail.com");
        person.setName("xl");
        person.build().writeTo(new FileOutputStream("E:/person"));
      
    • 接收消息

        AddressBookProtos.Person person = AddressBookProtos.Person.parseFrom(new FileInputStream("E:/person"));
        System.out.println(person.getId());
        System.out.println(person.getName());
        System.out.println(person.getEmail());
        System.out.println(person.getContent());
      

    相关文章

      网友评论

          本文标题:protobuf使用

          本文链接:https://www.haomeiwen.com/subject/ljqmsftx.html