1-1-1 最佳實務
1-1-1 最佳實務是盡可能保持每個 proto_library 和 .proto 檔案小,理想情況是
- 一個
proto_library
建置規則 - 一個來源
.proto
檔案 - 一個最上層實體 (訊息、列舉或擴展)
盡可能減少訊息、列舉、擴展和服務的數量,可讓重構更容易。當檔案分離時,移動檔案比從包含其他訊息的檔案中提取訊息容易得多。
遵循此實務可以藉由減少您的傳遞依賴項的大小,來幫助縮短建置時間和二進位檔大小:當某些程式碼只需要使用一個列舉時,在 1-1-1 設計下,它可以僅依賴定義該列舉的 .proto 檔案,並避免意外地引入可能只由同一檔案中定義的另一個訊息使用的龐大傳遞依賴項集合。
在某些情況下,1-1-1 的理想情況是不可能的 (循環相依性)、不理想的 (概念上極度耦合的訊息,其共同定位具有可讀性優勢),或者某些缺點不適用 (當 .proto 檔案沒有匯入時,則不會有關於傳遞依賴項大小的技術問題)。與任何最佳實務一樣,請判斷何時應偏離該指南。
當建立 gRPC 定義時,proto 綱要檔案的模組化是一個重要的地方。以下一組 proto 檔案顯示模組化結構。
student_id.proto
edition = "2023";
package my.package;
message StudentID {
string value = 1;
}
full_name.proto
edition = "2023";
package my.package;
message FullName {
string family_name = 1;
string given_name = 2;
}
student.proto
edition = "2023";
package my.package;
import "student_id.proto";
import "full_name.proto";
message Student {
StudentId id = 1;
FullName name = 2;
}
create_student_request.proto
edition = "2023";
package my.package;
import "full_name.proto";
message CreateStudentRequest {
FullName name = 1;
}
create_student_response.proto
edition = "2023";
package my.package;
import "student.proto";
message CreateStudentResponse {
Student student = 1;
}
get_student_request.proto
edition = "2023";
package my.package;
import "student_id.proto";
message GetStudentRequest {
StudentID id = 1;
}
get_student_response.proto
edition = "2023";
package my.package;
import "student.proto";
message GetStudentResponse {
Student student = 1;
}
student_service.proto
edition = "2023";
package my.package;
import "create_student_request.proto";
import "create_student_response.proto";
import "get_student_request.proto";
import "get_student_response.proto";
service StudentService {
rpc CreateStudent(CreateStudentRequest) returns (CreateStudentResponse);
rpc GetStudent(GetStudentRequest) returns (GetStudentResponse);
}
服務定義和每個訊息定義都位於它們自己的檔案中,您可以使用 include 從其他綱要檔案存取訊息。
在此範例中,Student
、StudentID
和 FullName
是跨請求和回應可重複使用的網域類型。最上層的請求和回應 proto 對於每個服務 + 方法都是唯一的。
如果您稍後需要將 middle_name
欄位新增至 FullName
訊息,則不需要使用該新欄位更新每個最上層訊息。同樣地,如果您需要使用更多資訊更新 Student
,則所有請求和回應都會取得更新。此外,StudentID
可能會更新為多部分 ID。
最後,將像 StudentID
這樣的簡單類型包裝為訊息意味著您已建立具有語義和整合文件化的類型。對於像 FullName
這樣的事物,您需要小心此 PII 的記錄位置;這是不在多個最上層訊息中重複這些欄位的另一個優勢。您可以在一個地方將這些欄位標記為敏感,並將它們從記錄中排除。