.proto 파일 자체가 문법적으로 올바른지도 포함syntax = "proto3";
message SearchRequest {
optional string query = 1;
int32 page_number = 2;
repeated string filters = 3;
map<string, string> metadata = 4;
optional int32 results_per_page = 5;
}
syntax 명시message 포함 가능message를 하나의 파일에 정의하면 종속성 문제가 발생 가능.proto 파일당 가능한 한 적은 수의 메시지만 포함하는게 좋음1~536,870,911 사이의 숫자 지정1~15까지의 필드 번호를 사용19,000 ~ 19,999는 프로토콜 버퍼 구현을 위해 예약됨 optional
implicit(명시 안함)
optional을 명시하지 않으면 implicit으로 사용repeated
map
reserved 에 추가해 재사용 방지message Foo {
reserved 2, 15, 9 to 11;
}
message SearchResponse {
repeated Result results = 1;
}
message Result {
string url = 1;
string title = 2;
repeated string snippets = 3;
}
message SearchResponse {
message Result {
string url = 1;
string title = 2;
repeated string snippets = 3;
}
repeated Result results = 1;
}
message SomeOtherMessage {
SearchResponse.Result result = 1;
}
Parent.Type 으로 참조 가능enum도 다른 메시지에서 사용 가능MessageType.EnumType 과 같이 사용allow_alias 옵션을 true로 설정reserved 키워드 사용enum EnumAllowingAlias {
option allow_alias = true;
EAA_UNSPECIFIED = 0;
EAA_STARTED = 1;
EAA_RUNNING = 1;
EAA_FINISHED = 2;
}
map<key_type, value_type> map_field = N;
key_type double, float) 과 bytes 사용 불가value_type import "google/protobuf/any.proto";
message ErrorStatus {
string message = 1;
repeated google.protobuf.Any details = 2;
}
google/protobuf/any.proto 를 import 해야함message SampleMessage {
oneof test_oneof {
string name = 4;
SubMessage sub_message = 9;
}
}
oneof 필드 내의 모든 필드가 메모리를 공유oneof 필드 내의 멤버를 하나 설정하면 oneof 내의 다른 모든 멤버가 자동으로 삭제map 및 repeated를 제외한 모든 유형의 필드를 oneof에 추가 가능oneof 내 여러 필드의 값을 설정하는 경우 마지막으로 설정한 필드만 값을 유지.proto 파일에 정의된 메시지 타입을 필드 타입으로 사용하려면, 해당 .proto 파일을 import해야 함import "myproject/other_protos.proto";.proto 파일의 위치를 변경하면, 기존에 해당 파일을 import하던 모든 코드에서 import 경로를 수정해야 하는 번거로움이 발생import public을 사용하면, .proto 파일 배치 .proto 파일을 import public로 연결// old.proto
// This is the proto that all clients are importing.
import public "new.proto";
import "other.proto";
// client.proto
import "old.proto";
// You use definitions from old.proto and new.proto, but not other.proto
import public은 전이성을 가짐.proto 파일에서 RPC 서비스 인터페이스 정의 가능protoc 는 선택한 언어로 서비스 인터페이스 코드 및 stub을 생성 service SearchService {
rpc Search(SearchRequest) returns (SearchResponse);
}
SearchRequest를 매개변수로 갖고 SearchResponse를 반환하는 메소드 정의 가능service 정의 방법: 4가지 종류의 메소드 정의 가능rpc GetFeature(Point) returns (Feature) {}
// 서버 측 스트리밍 RPC
// 클라이언트는 더 이상 메시지가 없을때까지 스트림 읽음
rpc ListFeatures(Rectangle) returns (stream Feature) {}
// 클라이언트 측 스트리밍 RPC
// 클라이언트의 일련의 메시지 작성 및 서버 응답 대기
rpc RecordRoute(stream Point) returns (RouteSummary) {}
// 양방향 스트리밍 RPC
// 클라이언트, 서버가 독립적이기 때문에 원하는 순서대로 읽고 쓰기 가능
rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}