【问题标题】:How to return an array in Protobuf service rpc如何在 Protobuf 服务 rpc 中返回一个数组
【发布时间】:2017-08-27 07:46:34
【问题描述】:

我的.proto 文件中有以下架构:

service MyService {
    rpc GetItem (ItemQuery) returns (Item) {
    }
}

message ItemQuery {
    int id = 1;
}
message Item {
    int id = 1;
    string name = 2;
}

现在我想添加另一个 rpc 方法来返回多个项目。 像这样:

rpc GetItems (ItemsQuery) returns (repeated Item) {
}

有没有比定义 Items 消息更好的方法?

【问题讨论】:

    标签: protocol-buffers rpc


    【解决方案1】:

    选项 1 - 使用流:

    rpc GetItems (ItemsQuery) returns (stream Item) {
    }
    

    选项 2 - 设置将使用重复对象的响应消息:

    service MyService {
        rpc GetItem (ItemQuery) returns (ItemResponse) {
        }
    }
    
    message ItemQuery {
        int id = 1;
    }
    message ItemResponse {
        repeated Item items = 1;
    }
    message Item {
        int id = 1;
        string name = 2;
    }
    

    【讨论】:

    • 我迟到了,但是:选项 2 是否比选项 1 有任何优势,反之亦然?
    • 选项 1 是一个流,这意味着您正在返回一个迭代器,这意味着您甚至可以在服务器完成发送所有项目之前开始在客户端处理项目。选项 2 是一个响应对象,其中包含您的项目列表。您可以向 ItemResponse 添加一些其他属性(一些元数据等)...
    • 嗨,我们是否可以返回一个无键数组响应作为 gRPC 中的响应?我试过直播,但没有帮助。
    • 适用于:message GetChannelsResponse {repeated string channel_name = 1;}
    猜你喜欢
    • 1970-01-01
    • 2016-06-09
    • 2015-06-23
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多