登录
首页 >  Golang >  Go问答

如何有效组织原型文件以便重复利用消息?

来源:stackoverflow

时间:2024-03-03 21:57:27 346浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《如何有效组织原型文件以便重复利用消息?》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我最近开始在我的 golang 项目中使用 protobuf。我创建了下面简单的 protobuf 文件。我有三个不同的端点。

  • getlinkcustomerrequest 作为输入参数并返回 customerresponse
  • getbulklinksbulkcustomerrequest 作为输入参数并返回 bulkcustomerresponse
  • strealinksstreamrequest 作为输入参数并返回 customerresponse

我想知道是否有任何方法可以改进下面的原型文件,因为 customerrequestbulkcustomerrequest 几乎所有内容都是相同的,除了 resources 字段之外,因此存在重复。 streamrequest 输入参数也是如此,因为它仅将 clientid 作为输入参数。协议缓冲区中是否有任何内容可以重用其他消息类型的内容?

有没有更好或更有效的方法来组织下面的原型文件,从而相应地重用消息?

syntax = "proto3";

option go_package = "github.com/david/customerclient/gen/go/data/v1";

package data.v1;

service CustomerService {
  rpc GetLink(CustomerRequest) returns (CustomerResponse) {};
  rpc GetBulkLinks(BulkCustomerRequest) returns (BulkCustomerResponse) {};
  rpc StreaLinks(StreamRequest) returns (CustomerResponse) {};
}

message CustomerRequest {
  int32 clientId = 1;
  string resources = 2;
  bool isProcess = 3;
}

message BulkCustomerRequest {
  int32 clientId = 1;
  repeated string resources = 2;
  bool isProcess = 3;
}

message StreamRequest {
  int32 clientId = 1;
}

message CustomerResponse {
  string value = 1;
  string info = 2;
  string baseInfo = 3;
  string link = 4;
}

message BulkCustomerResponse {
  map customerResponse = 1;
}

正确答案


协议缓冲区中是否有任何内容可以重用其他消息类型的内容?

Composition

但是请记住,请求和响应有效负载可能会随着时间的推移而发生变化。即使它们今天看起来有一些共同点,明天它们也可能会出现分歧。 毕竟它们用于不同的 rpc。那么过度的耦合就会达到相反的效果,成为技术债务。

由于您的架构实际上每条消息的字段不超过三个,因此我将保留所有内容不变。无论如何,如果你确实必须这样做,你可以考虑以下几点:

  • 在单独的消息中提取 getlinkgetbulklinks 公共字段并与之组合:
message CustomerRequestParams {
  int32 clientId = 1;
  bool isProcess = 2;
}

message CustomerRequest {
  CustomerRequestParams params = 1;
  string resources = 2;
}

message BulkCustomerRequest {
  CustomerRequestParams params = 1;
  repeated string resources = 2;
}
  • streamrequest 看起来与重复 clientid 没问题。可以说,流在概念上与一元 rpc 不同,因此只需将它们分开即可。而且这只是一个字段。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>