如何在 gcloud pubsub 中为主题添加 protobuf 文件?
how to add protobuf file for topic in gcloud pubsub?
在google云的pubsub中,我可以看到在创建新主题时,我必须创建一条新消息。我可以在那里存储一个 protobuf 文件,而不必在键值对中编写整个消息结构吗?对于应该编写的 protobuf 代码,我的意思是 this。如果 protobuf 不打算放在 gcloud pubsub 上,我如何将它与 grpc 客户端一起使用?
如果您想通过 Publish
API 发送 ProtoBuf 消息,您应该将其序列化为 ByteString
然后将其设置为消息的 [=14] =] 字段。例如,如果您正在使用某些 ProtoBuf 类型的 Java client library and you have a Publisher
和 obj
,那么您可以执行以下操作:
PubsubMessage message = PubsubMessage.newBuilder()
.setData(obj.toByteString())
.build();
ApiFuture<String> response = publisher.publish(message);
...
在订阅方,您将解码 MessageReceiver:
中的消息
public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
ProtoBufMessage obj;
try {
obj = ProtoBufMessage.parseFrom(message.getData());
} catch (Exception e) {
// Handle improperly encoded message
}
...
}
在google云的pubsub中,我可以看到在创建新主题时,我必须创建一条新消息。我可以在那里存储一个 protobuf 文件,而不必在键值对中编写整个消息结构吗?对于应该编写的 protobuf 代码,我的意思是 this。如果 protobuf 不打算放在 gcloud pubsub 上,我如何将它与 grpc 客户端一起使用?
如果您想通过 Publish
API 发送 ProtoBuf 消息,您应该将其序列化为 ByteString
然后将其设置为消息的 [=14] =] 字段。例如,如果您正在使用某些 ProtoBuf 类型的 Java client library and you have a Publisher
和 obj
,那么您可以执行以下操作:
PubsubMessage message = PubsubMessage.newBuilder()
.setData(obj.toByteString())
.build();
ApiFuture<String> response = publisher.publish(message);
...
在订阅方,您将解码 MessageReceiver:
中的消息public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
ProtoBufMessage obj;
try {
obj = ProtoBufMessage.parseFrom(message.getData());
} catch (Exception e) {
// Handle improperly encoded message
}
...
}