【问题标题】:Protobuf - Replacing a generic CollectionProtobuf - 替换通用集合
【发布时间】:2021-04-18 06:46:30
【问题描述】:

我在 .Net Core 3.1 中使用 C#。我有一个类,用于现有项目/其他 API:

/// <summary>Class representing a Result Set (data coming from a result page,
/// plus the total count of the records coming from all the resulting pages) </summary>
/// <typeparam name="T">The class type of the result set</typeparam>
public class PagedResult<T>
{
    /// <summary> Total number of rows in the result set </summary>
    public long TotalRows { get; set; }

    /// <summary> IList containing the data of the requested page's result set  </summary>
    public IList<T> PageData { get; set; } = new List<T>();
}

我将它用作许多消息的返回类型(基本上是每个分页查询)。

如何在 gRPC / Protobuf 中替换类似的内容?

我可以想到以下几点:

message PagedResult
{
  int32 total_rows = 1;
  repeated google.protobuf.Any page_data = 2;
}

但这将要求我将每个结果都视为不同。 另一种方法是为每个 page_data 类型创建一条新消息:

message MyEntityPagedResult
{
  int32 total_rows = 1;
  repeated MyEntity page_data = 2;
}

我知道 protobuf 不支持继承,但是有没有办法管理这种响应而不在 proto 中插入大量样板?有什么建议吗?

谢谢!

【问题讨论】:

  • 你可以考虑使用protobuf.net,我认为处理泛型和继承就好了。我没有用gRPC,但是有一个protobuf-net.Grpc包。
  • 确实,使用 protobuf-net.Grpc,在那里敲一些 [ProtoContract]/[ProtoMember(N)] 属性,然后:你完成了。 gRPC 边界可以通过接口来描述,工作完成

标签: c# .net-core protocol-buffers grpc


【解决方案1】:


你可以尝试像这样在你的 shell protobuf 中使用 Any 关键字

message MyEntityPagedResult
{
  int32 total_rows = 1;
  any page_data = 2;
}

而你的 C# 客户端和服务器端你可以改变这个 Any type 这样的

// Read Person message from detail.
if (status.page_data.Is(__YourClassType__))
{
    var person = status.page_data.Unpack<__YourClassType__>();
    ...
}

注意:在此解决方案中,YourClassType 必须在 proto 中定义为消息类。这可以在我看来,没有任何方法可以在 proto 文件中实现类似类型:/

编辑: 此链接还可以提供有关您的问题的详细信息。 :) 好好编码:D

【讨论】:

  • 谢谢!这是我要尝试的一条路线,主要是因为公司原因我想尽可能坚持“仅限微软”,所以我不能使用 Protobuf.Net(看起来非常,非常 i> 很好)。
  • 我很乐意帮助您解决问题。顺便说一下,这个解决方案有点难,但是在协议中创建了一个结构和层次结构。另外,我忘记了上面显示的图像链接的链接。 docs.microsoft.com/en-us/aspnet/core/grpc/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多