繁体   English   中英

如何使用协议缓冲区?

[英]how use protocol buffers?

我看了很多教程,但我不明白如何使用协议缓冲区

为什么是“消息用户”? 为什么不是“类用户”? Eclipse 是如何创建这样的消息的? 为什么 name = 2 ? 不是名字=“最大”

ption java_outer_classname="ProtoUser";

message User {

   required int32  id = 1;  // DB record ID
   required string name = 2;
   required string firstname = 3;
   required string lastname = 4;
   required string ssn= 5; 



   // Embedded Address message spec

    message Address {
      required int32 id = 1;
      required string country = 2 [default = "US"];; 
      optional string state = 3;
      optional string city = 4;
      optional string street = 5;
      optional string zip = 6;



      enum Type {
         HOME = 0;

         WORK = 1; 

       }

       optional Type addrType = 7 [default = HOME]; 

 }
   repeated Address addr = 16;
}

为什么是“消息用户”? 为什么不是“类用户”?

Google Protocol Buffers (GPB) 在其语法中没有class ,而是有message https://developers.google.com/protocol-buffers/docs/style

这个文件只是文本文件,它应该有.proto扩展名。 毕竟,您将在其上运行一个实用程序,它会生成真正的 Java 类,您可以导入这些类并在您的项目中轻松使用。

https://developers.google.com/protocol-buffers/docs/javatutorial

编译您的协议缓冲区

protoc -I=$SRC_DIR --java_out=$DST_DIR $SRC_DIR/addressbook.proto

required string lastname = 4;

4 代表字段 id ,不是值,它将用于生成比特流。

Protobuffer 使用 message(keyword) 而不是 class 在您定义结构的类内部。 架构。 例如

 message Person{
  string name = 1;
  repeated string id = 2;
  Type phoneType = 3;
 }

enum Type{
 CellPhone = 0;
 HomePhone = 1;
 }

在上面的例子中,我们定义了 Person Message 的结构。 它有 name 数据类型是字符串,id 是字符串和类型的数组(当您只期望某些值时,则使用枚举。在这种情况下,我们假设 phoneNumber 可以是 CellPhone 或 HomePhone。如果有人正在发送任何其他值,那么它将通过 UNKNOWN proto 值异常)

required:表示需要参数

要使用 proto 首先使用 mvn clean install 创建 proto 类然后创建 protobuilder Protobuilder 来设置上面的 proto

 Person person = Person.newBuilder().setName("testName")
 .setPhoneType(Type.CellPhone)
 .addAllId(listIds)
 .build;

一旦您设置了该值,您将无法更改它。 如果要更改该值,则需要创建另一个原型。 Pesron person1 = Person.newBuilder(person).setName("ChangeName").build;

person1 将具有名称 ChangeName、phoneType CellPhone 和 ids 字符串数组。

更多信息: https : //developers.google.com/protocol-buffers

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM