Protobuf 개요
C++
,C#
,Go
,Java
,Python
등 다양한 언어를 지원.장점
단점
.proto
파일이 꼭 있어야 하며 아니면 무슨 의미인지 모른다. 그래서 내부간의 데이터 교환에 자주 쓰인다.Protocol buffer 문법
(제가 사용하는 언어가 scala라 scala로 이해해보겠습니다.)
syntax : proto2
, proto3
를 사용할지는 .proto파일의 첫줄에 있어야한다.
package : 자바(스칼라)의 package와 동일.
message : 스칼라의 case class
와 동일.
필드 타입 출처(https://minusi.tistory.com)
required : message는 해당 필드를 정확하게 1개만 가진다.
optional : message는 해당 필드를 가지지 않을수도, 1개만 가질수도 있다.
repeated : 스칼라의 List
와 동일. 만약 message 2번째 필드에 list : List[Int]
를 추가하고싶으면 repeated int32 list = 2
map : 스칼라의 Map
과 동일. 만약 message의 3번째 필드에 map : Map[Int, String]
을 추가하고 싶으면 map<int32, string> map = 3
로 표기
예시
syntax = "proto3";
package com.scala.test;
message TTT{
int32 t1 = 1;
}
message Test{
int32 x1 = 1;
repeated int32 list = 2;
map<int32, string> map = 3;
TTT ttt = 4; // TTT를 타입으로 가진 필드
repeated TTT tlist = 5; // List[TTT] 필드
}
이 코드를 scalapb gradle
플러그인으로 변환하면 다음과 같다. (일부 발췌)
final case class Test(
x1: _root_.scala.Int = 0,
list: _root_.scala.Seq[_root_.scala.Int] = _root_.scala.Seq.empty,
map: _root_.scala.collection.immutable.Map[_root_.scala.Int, _root_.scala.Predef.String] = _root_.scala.collection.immutable.Map.empty,
ttt: _root_.scala.Option[com.scala.test.test.TTT] = _root_.scala.None,
tlist: _root_.scala.Seq[com.scala.test.test.TTT] = _root_.scala.Seq.empty,
unknownFields: _root_.scalapb.UnknownFieldSet = _root_.scalapb.UnknownFieldSet.empty
) extends scalapb.GeneratedMessage with scalapb.lenses.Updatable[Test] ...
.proto -> scala로 변환 (with. scalapb)
Intellij
로 실행하면 .proto 파일에서 변환된 스칼라 파일이 나온다. (build
디렉토리)