Protobuf

作者: jsjack_wang | 来源:发表于2018-03-09 20:45 被阅读0次
    1.maven
    <dependency>
      <groupId>com.google.protobuf</groupId>
      <artifactId>protobuf-java</artifactId>
      <version>3.3.0</version>
    </dependency>
    
    2.编辑person_entity.proto文件
    syntax = "proto2";
    
    option java_package = "com.boomsecret.protobuf.proto";
    option java_outer_classname = "PersonEntity";
    
    message person_entity {
        required int32 id = 1;  // ID
        required string name = 2;   // 姓名
        optional string email = 3;  // 邮箱
    }
    
    3.下载protoc.exe,并生成.java文件
    https://github.com/google/protobuf/releases
    protoc.exe --java_out=.\..\src\main\java .\proto\person_entity.proto
    
    (com.boomsecret.protobuf.proto.PersonEntity.java)
    
    4.小李子
    public class ProtoBufDemo {
        public static void main(String[] args) {
            PersonEntity.person_entity.Builder builder = PersonEntity.person_entity.newBuilder();
            builder.setId(100);
            builder.setName("jack");
            builder.setEmail("jack@email.com");
    
            person_entity personEntity = builder.build();
            System.out.println(personEntity.toString());
    
            byte[] bytes = personEntity.toByteArray();
            for (byte index : bytes) {
                System.out.print(index);
            }
            System.out.println();
    
            try {
                person_entity parsePersonEntity = person_entity.parseFrom(bytes);
                System.out.println(parsePersonEntity);
            } catch (InvalidProtocolBufferException e) {
                e.printStackTrace();
            }
        }
    }
    
    5.总结
    protobuf比xml和json效率高很多,具体可以去了解下,这里不做详细介绍。

    相关文章

      网友评论

          本文标题:Protobuf

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