将 ProtoBuf-net 与 gRPC 结合使用 [英] Using ProtoBuf-net with gRPC
问题描述
我正在尝试构建一个使用 gRPC 的 PoC.谷歌文档这里 为我们提供了一个示例应用程序.我想知道 protobuf-net,特别是 protogen,是否有能力理解执行 gRPC 调用所需的服务定义和类?或者这是正在处理的事情?如果我将 google 的 protoc 用于客户端和服务器代码生成(涉及服务定义和 RPC 调用),并为我的业务对象使用 protobuf-net,它会起作用吗.
I am trying to build a PoC at work that utilizes gRPC. The google document here takes us through a sample application. I was wondering if protobuf-net, and specifically protogen, had the capability to understand service definitions and classes necessary to perform gRPC calls? Or is this something being worked on? Would it work if I use google's protoc for client and server code generation(which involves the service definitions and RPC calls) and protobuf-net for my business objects.
推荐答案
protobuf-net.Grpc 现在是一个东西......尽管在预览中.当 .NET Core 3 出来时,我们应该能够提供它.
protobuf-net.Grpc is now a thing... albeit in preview. When .NET Core 3 comes out, we should be able to make this available.
它受到 WCF 方法的启发,因此您的服务接口是通过以下方式定义的:
It is inspired by the WCF approach, so your service interfaces are defined via:
namespace Whatever {
[ServiceContract]
public interface IMyAmazingService {
ValueTask<SearchResponse> SearchAsync(SearchRequest request);
// ... etc
}
}
服务器只是实现接口:
public class MyServer : IMyAmazingService {
// ...
}
(托管它们的方式取决于您使用的是 ASP.NET Core 还是本机/非托管 gRPC 库;两者都有效)
(how you host them depends on whether you're using ASP.NET Core, or the native/unmanaged gRPC libraries; both work)
和客户端只是请求接口:
var client = http.CreateGrpcService<IMyAmazingService>();
var result = await client.SearchAsync(query);
在上述情况下,这将被推断为 gRPC 术语中的 Whatever.MyAmazingService
/Search
服务,即
In the above case, this would be inferred to be the Whatever.MyAmazingService
/ Search
service in gRPC terms, i.e.
package Whatever;
// ...
service MyAmazingService {
rpc Search (SearchRequest) returns (SearchResponse) {}
}
但是如果您愿意,可以更明确地配置服务/方法名称.上面是一个一元的例子;对于一元运算,结果可以是 T
、Task
、ValueTask
- 或 void
/Task
/ValueTask
(它们都映射到 .google.protobuf.Empty
,没有合适的输入参数的方法也是如此).
but the service/method names can be configured more explicitly if you prefer. The above is a unary example; for unary operations, the result can be any of T
, Task<T>
, ValueTask<T>
- or void
/ Task
/ ValueTask
(which all map to .google.protobuf.Empty
, as does a method without a suitable input parameter).
如果您使用 IAsyncEnumerable
(对于某些 T
)作为输入参数(client-streaming),则自动推断流/双工操作,返回类型(服务器流式传输),或两者(双工).
The streaming/duplex operations are inferred automatically if you use IAsyncEnumerable<T>
(for some T
) for the input parameter (client-streaming), the return type (server-streaming), or both (duplex).
这篇关于将 ProtoBuf-net 与 gRPC 结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!