如何知道字节数组是哪个protobuf消息? [英] How to know which protobuf message the byte array is?

查看:946
本文介绍了如何知道字节数组是哪个protobuf消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用protobuf而不是Json在消息队列之间进行通信.

I want to use protobuf instead of Json to communicate between message queue.

只有一条原始消息时,我知道如何处理.

I know how to deal with it when there is only one proto message.

假定原始文件为:

//person.proto
syntax = "proto3";

option java_outer_classname = "PersonProto";

message Person {
    int32 id = 2;
    string name = 1;
    string email = 3;
}

现在,我可以使用以下方法来处理它:

Now, i can deal with it with the approach below:

PersonProto.Person person = PersonProto.Person.newBuilder()
        .setEmail("123@test.com")
        .setId(1)
        .setName("name-test")
        .build();

byte[] bytes = person.toByteArray();

//Transfer from publisher to consumer between message queue.

//I can deserialise it, because i know the proto message is Person.
PersonProto.Person.parseFrom(bytes);

但是如果有多个原始消息怎么办?

But what if there are multiple proto messages?

假设还有另一条称为Address的原始消息.

Assume that there is another proto message called Address.

syntax = "proto3";

option java_outer_classname = "PersonProto";

message Person {
    int32 id = 2;
    string name = 1;
    string email = 3;
}

message Address {
    string address = 1;
}

当消费者从消息队列接收字节数组时,如何知道它是哪个原始消息?以及如何反序列化字节数组?

When consumer received byte array from message queue, how to know which proto message it is? and how to deserialise the byte array?

推荐答案

Protobuf 3引入了

Protobuf 3 introduced the concept of Any that can act in a similar way to the top-level-message pattern explained by @AdamCozzette.

在写信方面,您可以将邮件打包在任何中:

On the write-side you pack your message in an Any:

Person person = ...
Any any = Any.pack(person);

out.write(any.toByteArray());

然后在读取面上读入任何,然后开启您感兴趣的类型:

Then on the read-side you read into an Any and switch on the types you are interested in:

Any any = Any.parseFrom(in);

if (any.is(Person.class)
{
  Person person = any.unpack(Person.class);
  ...
}
else if (any.is(Address.class);
{
  Address address = any.unpack(Address.class);
  ...
}
else
{
  //Handle unknown message
}

使用任何都无需使用特殊的消息类型( top-level-message ),而且还会删除类型安全元素,因为您可能会收到消耗代码不知道如何处理的消息.

Using Any removes the need for special a message type (the top-level-message), but also removes an element of type-safety in as much as you may receive messages that the consuming code does not know how to handle.

这篇关于如何知道字节数组是哪个protobuf消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆