[英]Returning a list of messages
Given that i have multiple models, each needed to have their own create/get/get list API.鉴于我有多个模型,每个模型都需要有自己的创建/获取/获取列表 API。 Do i need to add two different types of messages (single and list) for every model?
我是否需要为每个模型添加两种不同类型的消息(单个和列表)?
For example : If i have a student type -例如:如果我有一个学生类型 -
message Student{
string name = 1;
}
and a rpc:和一个rpc:
rpc CreateStudent(Student) returns (google.protobuf.Empty){
..............
}
If i'd like to add a rpc to create a list of students, or get a list of students如果我想添加 rpc 来创建学生列表,或获取学生列表
rpc CreateStudends(??????) returns (google.protobuf.Empty){
..............
}
rpc GetAllStudents() returns (??????){
..............
}
Do i need to also define我是否还需要定义
message StudentList{
repeated Student students = 1;
}
Or is there a way to use a list type directly in the message input/output?或者有没有办法直接在消息输入/输出中使用列表类型?
Yes, basically - you would want a different message type per element type, or maybe a single root type with a oneof
style content.是的,基本上 - 您希望每个元素类型都有不同的消息类型,或者可能是具有
oneof
样式内容的单个根类型。 Raw protobuf does not include a concept of generics or templates.原始 protobuf 不包括泛型或模板的概念。
Some libraries do, but: that's outside of the specification.一些库可以,但是:这超出了规范。
You can simply add the stream
keyword to your RPCs.您可以简单地将
stream
关键字添加到您的 RPC 中。 No need to define a message field as repeated, stream
will send or receive multiple independent messages.无需将消息字段定义为重复,
stream
将发送或接收多个独立的消息。
message Student {
string name = 1;
}
with RPCs:使用 RPC:
rpc CreateStudent(Student) returns (google.protobuf.Empty) {
..............
}
rpc CreateStudents(stream Student) returns (google.protobuf.Empty) {
..............
}
rpc GetAllStudents() returns (stream Student) {
..............
}
It's good practice to send/stream a response object rather than empty.发送/流式传输响应对象而不是空是一种很好的做法。 Otherwise, you only have the gRPC response code to indicate a problem and will need to reference the logs to debug.
否则,您只有 gRPC 响应代码来指示问题,并且需要参考日志进行调试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.