【问题标题】:Is there any way to implement extend with proto3?有没有办法用 proto3 实现扩展?
【发布时间】:2017-09-19 10:38:58
【问题描述】:

因为proto3中没有extend,所以我把基础消息和google.protobuf.Any类型的消息结合起来,但是它的二进制长度太长了

.proto 文件

message TradeMessage {  
     google.protobuf.Any message = 1;  
     string code = 2;
}  
message Connect {
     int32 seq = 1;
     string appid = 2;
     string clientid = 3;
     string ver = 4;
}
...

.java 文件

TradeProtocol.Connect inner = TradeProtocol.Connect.newBuilder()
                    .setSeq(1)
                    .setAppid("test")
                    .build();

TradeProtocol.TradeMessage packet = TradeProtocol.TradeMessage.newBuilder()
                    .setMessage(Any.pack(inner))
                    .setCode(2)
                    .build();

服务向客户端发送数据包,客户端可以将所有消息解码到基础TradeMessage,问题是内部的长度是8字节,而数据包的长度是56字节。相同的功能实现使用proto2 的扩展仅十个字节,那么有什么方法可以在proto3 中实现扩展功能或减少数据包的长度?谢谢

【问题讨论】:

    标签: protocol-buffers


    【解决方案1】:

    另一种方法是使用 oneof:

    message Connect {
         int32 seq = 1;
         string appid = 2;
         string clientid = 3;
         string ver = 4;
    }
    
    message TradeMessage {  
         string code = 1;
         oneof inner {
              Connect inner_connect = 2;
              SomeOtherMessage inner_other = 3;
              ...
         }
    }  
    

    编码后的大小仍将比extend 大,但仅大 1-2 个字节。

    【讨论】:

      猜你喜欢
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-02
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      相关资源
      最近更新 更多