【问题标题】:Straightforward way to store protobuf java object in Mongodb?在 Mongodb 中存储 protobuf java 对象的简单方法?
【发布时间】:2023-03-08 19:29:01
【问题描述】:

当需要存储以 Java 实例形式(来自生成的 java 类)的 protobuf3 消息时,最好的选择是存储对象本身,然后再从数据库中读取。

我的用例是将此类消息存储在 Mongodb 中。 在调查这个的时候,我找不到办法,所以决定在这里问。

【问题讨论】:

    标签: mongodb protocol-buffers mongodb-java proto protobuf-java


    【解决方案1】:

    您可以将 Protobufs Java 类转换为 JSON,从 JSON 转换为 org.bson.Document,然后编写文档并在读取时反转该转换。

    更多详情请见JsonFormat

    下面是写端的一个简单示例:

    YourProtobufsClass anInstance = YourProtobufsClass.getDefaultInstance();
    
    String json = JsonFormat.printer().print(yourProtobufsClass); 
    
    Document document = Document.parse(json);
    
    mongoClient.getDatabase(...).getCollection(...).insertOne(document);
    

    下面是读取端的一个简单示例:

    JsonFormat.Parser parser = JsonFormat.parser();
    
    FindIterable<Document> documents = collection.find(...);
    for (Document document : documents) {
      YourProtobufsClass.Builder builder = YourProtobufsClass.newBuilder();
    
      parser.merge(document.toJson(), builder);
    
      // now you can build an instance of your protobufs class which 
      // has been populated from the retrieved JSON
      YourProtobufsClass anInstance = builder.build();
    }
    

    【讨论】:

    • 使用上述方式将 Protobufs java 类存储到 mongo db 中。它会抛出 No field is annotated with @Id; but it is requiredorg.mongodb.morphia.mapping.validation.ConstraintViolationException: Number of violations: 1 错误
    • 该错误与使用morphia 作为 Java 代码层和 MongoDB 之间的中介有关。最初的问题(和答案)根本不涉及morphia
    • 你能帮我吗?
    • 嗨@glytching。只是想知道转换为 JSON 然后再转换为 BSON 是否会影响性能?有没有办法编写我自己的 proto-BSON 解析器?发现这个问题:github.com/protocolbuffers/protobuf/issues/2601.
    • @james.bondu 通过 JSON 转换为 BSON 肯定会增加执行时间。额外的时间是否会“影响性能”可能只有您自己才能知道,因为您可以确定您的系统是否能够承受额外的时间。
    猜你喜欢
    • 2014-01-14
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 2023-04-10
    相关资源
    最近更新 更多