protobuf2简单介绍及在IDEA中的使用

一、protobuf2简单介绍

protobuf相较于xml和json,更注重于数据序列化
优点:拥有更高的时间效率和空间效率
缺点:可读性差
1. 数据类型
.proto Notes Java
double double
float float
int32 使用可变长度编码。编码负数的效率低 - 如果你的字段可能有负值,请改用 sint32 int
int64 使用可变长度编码。编码负数的效率低 - 如果你的字段可能有负值,请改用 sint64 long
uint32 使用可变长度编码 int
uint64 使用可变长度编码 long
sint32 使用可变长度编码。有符号的 int 值。这些比常规 int32 对负数能更有效地编码 int
sint64 使用可变长度编码。有符号的 int 值。这些比常规 int64 对负数能更有效地编码 long
fixed32 总是四个字节。如果值通常大于 228,则比 uint32 更有效。 int
fixed64 总是八个字节。如果值通常大于 256,则比 uint64 更有效。 long
sfixed32 总是四个字节 int
sfixed64 总是八个字节 long
bool boolean
string 字符串必须始终包含 UTF-8 编码或 7 位 ASCII 文本 String
bytes 可以包含任意字节序列 ByteString
2. 简单示例

proto2.proto

syntax = "proto2"; //proto版本,如果未添加,编译时会有警告,提示添加版本
package proto;
import "car.proto"; //引入外部proto文件,并让引入了该文件的proto文件也能访问被引入类型。需要在IDEA的settings-ProtocolBuffers中设置proto文件路径

option java_package = "cn.vic.entity"; //编译后,生成的java包名
option java_outer_classname = "PersonPB"; //编译后,生成的java类名,不能与message重名
option optimize_for = SPEED; //设置编译优化级别,SPEED-默认值速度优先,CODE_SIZE-最小代码量,LITE_RUNTIME-最小运行时占用(适用于环境受限的情况)

message Person {
  required string      id    = 1; //required表示字段必填
  repeated int32       age   = 2 [packed = true]; //基本数字类型的重复字段上设置packed,则一个更紧凑的编码被使用
  repeated PhoneNumber phone = 3; //repeated表示重复任意多次;在获取时应循环遍历
  optional string      name  = 4 [default = "未知", deprecated = true]; //optional表示字段选填;default表示默认值
  optional bool        marry = 5 [deprecated = true]; //deprecated表示字段已弃用,只是发出警告,不能阻止使用;如果任何人都未使用该字段,并且你希望阻止新用户使用该字段,请考虑使用 reserved 替换字段声明。
  optional Address     add   = 6; //message引用
  optional Car         car   = 7; //引用外部message

  extensions 8 to 10; //预定义8-10为extension字段;Extension有点类似继承,可以向message对象内增加额外的字段

  message Address {
    optional string city   = 1;
    optional string street = 2;
  }

  optional education   edu   = 11;

}

extend Person { //扩展
  optional int64 money = 8; //增加money字段,将编号100的字段插入到Person
}

message education {

  oneof edu_oneof { //如果你的message包含许多可选字段,并且最多只能同时设置其中一个字段,则可以使用oneof功能强制执行此行为并节省内存。:
    bool high_school = 1; //如果设置了high,那么weight字段将会被删除
    bool bachelor  = 3;
  }
  
  reserved 2, 15, 9 to 11; //预留
  reserved "master", "doctor"; //预留字段名
  
}

enum PhoneType{ //枚举
  MOBILE = 0;
  HOME   = 1;
  WORK   = 2;
}

message PhoneNumber {
  required string         number = 1;
  optional PhoneType      type   = 2 [default = HOME];
  optional Person.Address add    = 3; //引用外部message
}

car.proto

syntax = "proto2"; //proto版本
package proto;
option java_package = "cn.vic.entity";
option java_outer_classname = "Car2";

message Car {
  required int32 id = 1;
  required string vin = 2;
  optional string driver = 3;
  optional string job = 4;

  enum Sex {
    MAN = 0;
    WOMAN = 1;
  }
  optional Sex sex = 5 [default = MAN];

  enum PhoneType{
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }

  message PhoneNumber {
    required string number = 1;
    optional PhoneType type = 2 [default = HOME];
  }

  repeated PhoneNumber phone = 6;
  optional string brand = 7;
}

二、在IDEA中使用

1. 安装protobuf support
安装protobuf support以支持protobuf语法检查

在这里插入图片描述

.proto文件类型显示为蓝色的P

在这里插入图片描述

2. pom.xml添加maven插件
添加插件,以支持.proto文件转.java文件
    <build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.6.0</version>
            </extension>
        </extensions>
        <plugins>
            <!--protobuf maven插件,用于proto转java文件-->
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.6.1</version>
                <configuration>
                    <pluginId>java</pluginId>
                    <!--suppress UnresolvedMavenProperty -->
                    <protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}
                    </protocArtifact>
                    <protoSourceRoot>src/main/proto</protoSourceRoot>
                    <outputDirectory>${project.build.sourceDirectory}</outputDirectory>
                    <clearOutputDirectory>false</clearOutputDirectory>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile-javanano</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
添加后

在这里插入图片描述

3. pom.xml添加依赖
   <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <grpc.version>1.6.1</grpc.version>
        <protobuf.version>3.15.0</protobuf.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty</artifactId>
            <version>${grpc.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
            <version>${grpc.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
            <version>${grpc.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java</artifactId>
            <version>${protobuf.version}</version>
        </dependency>
        <!--protobuf转json-->
        <dependency>
            <groupId>com.googlecode.protobuf-java-format</groupId>
            <artifactId>protobuf-java-format</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
4. 添加.proto文件import path

在这里插入图片描述

5. 生成.java文件
点击 protobuf:compile 自动生成.java文件到指定路径
(在.proto文件中已经指定包名及类名,在maven插件添加时已经指定输出路径)

在这里插入图片描述

结果

在这里插入图片描述


以上为结合网上博客的个人测试,如有问题还请各位大神指教~


如发生报错

Failure to find com.google.protobuf:protoc:exe:${os.detected.classifier}:3.15.0 in https://repository.cloudera.com/artifactory/cloudera-repos was cached in the local repository, resolution will not be reattempted until the update interval of cloudera has elapsed or updates are forced

在pom的标签中添加以下内容即可解决

        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.6.2</version>
            </extension>
        </extensions>

相关文章

学习编程是顺着互联网的发展潮流,是一件好事。新手如何学习...
IT行业是什么工作做什么?IT行业的工作有:产品策划类、页面...
女生学Java好就业吗?女生适合学Java编程吗?目前有不少女生...
Can’t connect to local MySQL server through socket \'/v...
oracle基本命令 一、登录操作 1.管理员登录 # 管理员登录 ...
一、背景 因为项目中需要通北京网络,所以需要连vpn,但是服...