我可以使用null请求或响应定义grpc调用吗?

Mar*_*ahn 93 protocol-buffers grpc

proto3中的rpc语法是否允许空请求或响应?

例如,我想要相当于以下内容:

rpc Logout;
rpc Status returns (Status);
rpc Log (LogData);
Run Code Online (Sandbox Code Playgroud)

或者我应该只创建一个null类型?

message Null {};

rpc Logout (Null) returns (Null);
rpc Status (Null) returns (Status);
rpc Log (LogData) returns (Null);
Run Code Online (Sandbox Code Playgroud)

Mar*_*ahn 128

Kenton的评论如下是合理的建议:

......我们作为开发人员真的很难猜测未来我们可能会想要什么.所以我建议通过为每个方法定义自定义参数和结果类型来保证安全,即使它们是空的.


回答我自己的问题:

通过默认的proto文件,我遇到了Empty,这就像我上面建议的Null类型:)

从该文件中摘录:

// A generic empty message that you can re-use to avoid defining duplicated
// empty messages in your APIs. A typical example is to use it as the request
// or the response type of an API method. For instance:
//
//     service Foo {
//       rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
//     }
//

message Empty {

}
Run Code Online (Sandbox Code Playgroud)

  • @EricAnderson大多是正确的,但我认为我们作为开发人员在猜测未来我们可能想要的东西时非常糟糕.所以我建议通过为每个方法定义自定义参数和结果类型来保证安全,即使它们是空的. (35认同)
  • 是.空是规范的"我不关心"请求或响应.我会注意到,如果您认为_may_想要参数或将来返回值,请创建一个根本没有字段的新消息.这样,您可以在需要时添加新字段,而不会破坏任何应用程序代码.当您永远不需要参数或返回值时,Empty非常适合. (27认同)
  • `returns (google.protobuf.Empty);` 是否使调用非阻塞? (5认同)
  • GRPC 有线格式支持用具有向后兼容方式的字段的消息替换 Empty,因此您不需要新的空消息类型。拥有单独的消息可以使源代码级别变得更容易。请参阅 /sf/ask/3569567081/ (3认同)

hdn*_*dnn 73

您还可以使用预定义:

import "google/protobuf/empty.proto";
package MyPackage;

service MyService {
  rpc Check(google.protobuf.Empty) returns (google.protobuf.Empty) {}
}
Run Code Online (Sandbox Code Playgroud)