• Protocol Buffer Java实例


    大家要先下载protobuffer,在这里:

    https://code.google.com/p/protobuf/downloads/list

    注意,需要下载两个,一个是complier,另外一个是source code (我下载的是2.5的版本);

     

    讲complier对应的 protoc.exe 拷贝至 source code 对应的./protobuf-2.5.0/src目录下(mvn 编译需要);

    cd 到 ./protobuf-2.5.0/java 目录, 执行 mvn clean package 命令打包;

    到target目录获取生成的protobuf-java-2.5.0.jar包(Java代码对protobuf依赖的jar包);

    person.proto文件

    package com.shine.pb;
    option java_package = "com.shine.pb.person";
    option java_outer_classname = "MyPerson";
    
    message Person {
        required int32 id = 1;
        required string name = 2;
        optional string email = 3;
    
        enum PhoneType {
            MOBILE = 0;
            FIXED = 1;
        }
        
        message PhoneInfo {
            required string number = 1;
            required PhoneType type = 2 [default=MOBILE]; 
        }
        
        optional PhoneInfo phone = 4;
    }

    到protoc.exe所在目录,执行 protoc --java_out=./output/java ./messages/MyMessage.proto

    可生成proto文件对应的Java类;

    copy到自己eclipse对应src后;写main方法测试,代码如下:

    package com.shine.pb.person;
    
    import com.google.protobuf.InvalidProtocolBufferException;
    import com.shine.pb.person.MyPerson.Person.PhoneType;
    
    
    public class Test {
        
        public static void main(String[] args) throws InvalidProtocolBufferException {
            MyPerson.Person.Builder  builder = MyPerson.Person.newBuilder();
            builder.setId(1);
            builder.setName("shine");
            builder.setEmail("chenguodong@baidu.com");
            MyPerson.Person.PhoneInfo.Builder phoneInfoBuilder = MyPerson.Person.PhoneInfo.newBuilder();
            phoneInfoBuilder.setNumber("13899999999");
            phoneInfoBuilder.setType(PhoneType.MOBILE);
            builder.setPhone(phoneInfoBuilder.build());
            
            MyPerson.Person shine = builder.build();
            
            System.out.println(shine.getSerializedSize());
            System.out.println(shine.getEmail());
            System.out.println(shine.getName());
            System.out.println(shine.getPhone().getNumber());
            
            System.out.println("=============================================");
            
            byte[] data = shine.toByteArray();
            builder = MyPerson.Person.newBuilder();
            MyPerson.Person person = MyPerson.Person.parseFrom(data);
            System.out.println(person.getSerializedSize());
            System.out.println(person.getEmail());
            System.out.println(person.getName());
            System.out.println(person.getPhone().getNumber());
        }
    
    }
  • 相关阅读:
    cisco 4500X 交换机限速
    HPE 交换机基础配置
    MySQL数据库之主从复制
    MySQL复制线程状态转变
    MySQL数据库备份之mysqldump
    MySQL数据库之慢查询日志
    MySQL数据库之多线程备份工具mydumper
    MySQL数据库之索引
    MySQL之二进制日志
    MySQL数据库之sql_mode解释
  • 原文地址:https://www.cnblogs.com/shine_cn/p/4318980.html
Copyright © 2020-2023  润新知