一、簡介
proto3是新版本的protobuf語法。它簡化了部分語法,並擴大了支持的語言,Ruby、C#。目前谷歌推薦只在是用新支持的語言或使用新的gRPC框架的時候使用。
proto2和proto3不是完全兼容的。這里列出一些proto2與proto3的區別。
二、proto3
希望編譯器使用proto3進行編譯需要在文件對行加上:
syntax = "proto3";
下面是一個簡單的例子:
syntax = "proto3"; message Person { string name = 1; int32 age = 2; repeated string loction = 3; }
可以看到相比於proto2語法這里沒有前面的required/optional,在proto3中所有字段都是可選的,同時取消了自定義默認值,默認值為0或空。
枚舉
與proto2不同proto3的枚舉值第一個值得tag必須為0,同時枚舉值的默認值將默認使用第一個值,這樣就和其他類型都保持了統一,即默認值為0。
enum Location { SHANGHAI = 0; BEIJING = 1; GUANGZHOU = 2; }
同時proto2的枚舉類型不能被proto3直接import,但是間接引用不受影響。
Any
proto3不支持proto2中的extension,但是引入了Any。
在使用Any時需要引入any.proto:
import "google/protobuf/any.proto"; message ErrorStatus { string message = 1; repeated google.protobuf.Any details = 2; } ----------------------- public static void main(String[] args) throws IOException, ClassNotFoundException { //定義any Any any= Any.pack(StringValue.newBuilder().setValue("aaa").build()); //賦值並構建 Demo.Person person=Demo.Person.newBuilder().setDetail(any).build(); //取值 System.out.println(person.getDetail().unpack(StringValue.class)); }
三、其他
proto3去除了proto2中group,新增了一些timestamp、empty的格式(需要手動import)。