Should I create a message per method or use a shared message in gRPC?

故事扮演 提交于 2019-12-24 11:01:15

问题


Currently I'm using gRPC as the communication between my servers, but I don't know which is the best pattern.

Should I create a shared request message (UserRequest is treated like an User object):

service User {
    rpc Create (UserRequest) returns (Reply) {}
    rpc Update (UserRequest) returns (Reply) {}
    rpc Delete (UserRequest) returns (Reply) {}
}

message UserRequest {
    string username = 1;
    string password = 2;
    string email = 3;
    string gender = 4;
    string birthday = 5;
}

Or create a message per method like this to define the fields that the method actually needed? But since the methods are using almost the same fields, this is kinda verbose for me.

service User {
    rpc Create (CreateUserRequest) returns (Reply) {}
    rpc Update (UpdateUserRequest) returns (Reply) {}
    rpc Delete (DeleteUserRequest) returns (Reply) {}
}

message CreateUserRequest {
    string username = 1;
    string password = 2;
}

message UpdateUserRequest {
    string username = 1;
    string password = 2;
    string email = 3;
    string gender = 4;
    string birthday = 5;
}

//...

回答1:


Generally, create a different message for each RPC, to allow you to extend them separately. There are exceptions, but it would be unlikely when the methods do different things (create, update, delete).

As an example similar to your situation, take a look at pubsub:

rpc CreateSubscription(Subscription) returns (Subscription) {...}
rpc UpdateSubscription(UpdateSubscriptionRequest) returns (Subscription) {...}
rpc DeleteSubscription(DeleteSubscriptionRequest) returns (google.protobuf.Empty) {...}

I will note it uses google.protobuf.Empty, which I generally wouldn't suggest using for your own service as it prevents further extension. It also would have been fine to have created a CreateSubscriptionRequest that just contained a Subscription. I expect they didn't so as to make REST API to feel more natural (those google.api.http options).



来源:https://stackoverflow.com/questions/45934871/should-i-create-a-message-per-method-or-use-a-shared-message-in-grpc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!