将复杂java类建模为协议缓冲区

kognpnkq  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(351)

在协议缓冲区(.proto)中表示这一点的最佳方法是什么?

public class EntityId {
  private String type;
  private String id;  
}

public class EntityBlob {
  private String blobName;
  private byte[] blobBytes; 
}

public class Entity {
  private String dir;
  private String entityType;
  private String entityId;
  private Set<EntityBlob> blobs; 
  private Map<String,EntityProperty> properties;
  private Multimap<String, EntityId> relatedEntities;
}

public abstract class EntityProperty<T> {
  // ...
}

// Example concrete EntityProperty:
public class EntityStringProperty extends EntityProperty<String> {
  public EntityStringProperty(String value) {
    super(value);
  }
}

场地在哪里 properties 只能接受以下条件, EntityStringProperty , EntityBooleanProperty , EntityDoubleProperty 等等。
有一些特殊的课程:

public class EntityArrayProperty extends EntityProperty<List<EntityProperty>> {
  public EntityArrayProperty(List<EntityProperty> value) {
    super(value);
  }
}

public class EntityObjectProperty extends EntityProperty<Map<String, EntityProperty>> {
  public EntityObjectProperty(Map<String, EntityProperty> value) {
    super(value);
  }
}

如何用协议缓冲区对这个复杂的类进行建模?特别是 Map<String,EntityProperty> properties ?

bvjxkvbb

bvjxkvbb1#

这个 Map 属性还不错:protobuf支持Map。对于属性类型,您将使用一个消息 Package 其中一个。所以会像这样

message Entity {
  string dir = 1; 
  string entity_type = 2;
  string entity_id = 3;
  repeated EntityBlob blobs = 4;
  map<string, EntityProperty> properties = 5;
  map<string, EntityIdList> related_entities = 6;
}
message EntityProperty {
  oneof property_value {
    string string_value = 1;
    EntityArrayProperty array_value = 2;
    EntityObjectProperty object_value = 3;
    bool bool_value = 4;
    double double_value = 5;
  }
}
message EntityArrayProperty {
  repeated EntityProperty values = 1;
}
message EntityObjectProperty {
  map<string, EntityProperty> property_map = 1;
}
message EntityIdList {
  repeated EntityId ids = 1;
}
message EntityBlob {
  string blob_name = 1;
  bytes blob_bytes = 2;
}
message EntityId {
  string type = 1;
  string id = 2;
}

或者,它看起来像 EntityProperty 可能相当于 google.protobuf.Value ,因此您可能不必自己编写,但可以使用预定义的消息类型。

相关问题